Typescript - the type of assertion

Original: the typescript basic knowledge consolidation

 

Zero, Preamble

  Type assertion can be used to manually specify the type of a value.

  I feel, and casts like java in.

  And it is often combined with the use of the type, such as:

// 错误示例
function f13(name : string, age : string | number) {
     if (age.length) { //报错
         console.log(age.length) //报错
     }  else {
         console.log(age.toString)
     }

 }

 f13('ljy', 21)   
//Property 'length' does not exist on type 'string |number'.Property 'length' does not exist on type 'number'

// 使用类型断言示例
function f14(name : string, age : string | number) {
    if ((<string>age).length) {//断言
        console.log((<string>age).length)//断言
    }  else {
        console.log(age.toString)
    }

}
f14('ljy', 21)

 

Precautions:

  Type assertion is not cast in the ordinary sense, to assert a type union type that does not exist is not allowed:

function toBoolean(something: string | number): boolean {
    return <boolean>something;
}
// Type 'string | number' cannot be converted to type 'boolean'

 

Guess you like

Origin www.cnblogs.com/cc-freiheit/p/11051992.html