什么是TypeScript类型断言?
当TypeScript推断的类型不符合时,可以通过一定的语法人为进行类型推断即断言
断言的基本语法
as
看一种错误情形
let b = {}
b.name // Property 'name' does not exist on type '{}'
通过断言避免
let b = {} as { name: string}
b.name
< T >{}
interface Person {
name: string
}
let c = <Person>{}
c.name
在function中的应用
class Shape {}
class Circle extends Shape {}
function createShape(kind: string): Shape {
if (kind === "circle") return new Circle();
return new Shape()
}
var circle = <Circle>createShape("circle"); // circle
[x: string]: any
当声明了一个固定了属性的对象时,如果对象上有不存在的情况实会报错
interface Person {
name: string
}
let c = {
name: 'jack',
age: 11
}
可以通过类型断言避免
interface PersonAssertion {
name: string,
[key: string]: any
}
let d: PersonAssertion = {
name: 'jack',
age: 11
}
断言的缺点
当使用了断言时,是不会进行提示缺失的属性的
interface Person {
name: string
}
let c: Person = {} // 会提示缺失属性name而类型断言不会
双重类型断言
function handler(event: Event) {
let element = event as string; // 会报错,需要双重断言
}
function handler2(event: Event) {
let element = event as any as string;
}