常见类型 1 2 3 4 5 6 7 8 9 10 11 interface TEST { a?: string b?: number c?: boolean d?: any e?: (string | number )[] f?: () => void g?: {} h?: 'typescript' }
类型断言
类型只能被断言为一个更为具体或者更抽象的类型,而不是平级
1 2 3 4 5 6 const x = "hello" as number ; Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.const x = "hello" as {}
as const 后缀通常用来讲一个通用属性的类型转换为文字类型
1 2 3 4 5 6 7 8 const req = {url : 'https://www.aad.com' , method : 'Get' }const req = {url : 'https://www.aad.com' , method : 'Get' } as const
非空断言 通常当一个值为 undefined | null 时,可能需要去显示排除一下,使用非空断言可以明确排除空值
1 2 3 4 5 6 7 8 9 10 11 12 13 function doSomething (x?: string | null ) { console .log("Hello, " + x.toUpperCase()); }function doSomething (x?: string | null ) { console .log("Hello, " + x!.toUpperCase()); }function doSomething (x?: string | null ) { console .log("Hello, " + x?.toUpperCase()); }
类型缩小 通常当一个类型非常宽泛时,实际去使用时却要去具体到某一个类型,这时就要缩小类型,防止报错
typeof 类型守卫
1 2 3 4 5 function doSomething (x?: string | number | number [] ) { if (typeof x === 'object' ){ console .log(x.push(1 )) } }
真实性 收窄
1 2 3 4 5 function doSomething (x?: string ) { if (x){ console .log(x) } }
相等性收窄
1 2 3 4 5 function doSomething (x: string | number , y: string | boolean ) { if (x === y){ console .log(x.up) } }
in 运算符收窄
instanceof