type assertion [as syntax | <> syntax

Type assertions in TypeScript [as syntax | <> syntax]

https://huaweicloud.csdn.net/638f0fbbdacf622b8df8e283.html?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~activity-1-107633405-blog-122438115.235^v28^pc_relevant_t0_download&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~activity-1-107633405-blog-122438115.235^v28^pc_relevant_t0_download&utm_relevant_index=2

  • To understand type assertions well, you need to understand one sentence deeply: you will know more about the details of a value than TypeScript  .

  • Type assertion, assertion assertion, as the name suggests, I determine what, if it is substituted into this sentence, I determine what the type is. Of course, this is our subjective thinking logic, and the program does not recognize it, so we need to tell the program: "Trust me, I know what I am doing"  .

In this way, everyone may still not understand it thoroughly enough. I will use two functions to give an example:


/**
 * @param d 日期
 * @param f 想要格式化的字符串
 */
function dateFormatter(d: Date | string, f?: string) {
    const date = new Date(d);
    if (f) {
        return `${date.getFullYear()}${f}${date.getMonth() + 1}${f}${date.getDate()}`
    } else {
        return new Date(d);
    }
}

The above is a small function for simple date formatting. f is a connector. If f has a value, then use f to connect the date and return it. If there is no value, it will directly return a new Date(d).

/**
 * @param d 日期字符串
 */
function dealDate(d: string) {
    return new Date(d).getTime();
}

dealDate()The function accepts a string of type string and returns the milliseconds of this time.


Next, we first call the first dateFormatter() function, receive the return value, and then pass it to the dealDate() function, which is what we usually call at this time.

const date = dealDate(dateFormatter('2020-7-28', '/'));

The problem with this call is that we know that  the dateFormatter() function  f must return a string type because of the existence of parameters.

But TS doesn't think so. In the derivation of TS, the dateFormatter() function may return a Date type value, so it will give you a red mark to remind you that the dealDate() function needs to pass a string type value, but you pass It may be string or Date , and the type does not match.

But it can be compiled.

  • At this time, we meet the situation we mentioned earlier, and we can conclude that the passed string must be a string. At this point we can use:

    const date = dealDate(dateFormatter('2020-7-28','/') as string);
    
    // or use this
    const a = dealDate(<string>dateFormatter('2020-7-28', '/')); copy

This is type assertion in Typescript.

 

Guess you like

Origin blog.csdn.net/gcyaozuodashen/article/details/130062132