基础类型
类型断言
语法:
<type>variableName
或variableName as type
作用:明确告诉TS,这个变量就是这个类型,不要检查了
const iframe = document.getElementById('iframe-ele').contentWindow
当我作为 TS 初试小白敲下上面这行代码时,TS直接报错 Property 'contentWindow' does not exist on type 'HTMLElement'
。我深知 iframe DOM 有 contentWindow
属性,但 TS 不知,仍然将它作为普通的 HTMLElement
看待。
这个时候,就要用到 TS 的 类型断言 来明确告诉 TS:相信我,它就是 HTMLIFrameElement
类型。
const iframe = document.getElementById('iframe-ele') as HTMLIFrameElement
const iframeWindow = iframe.contentWindow // 顺利通过类型检查
接口 (interface)
额外的属性检查
语法:
[propName: type]: type
作用:对不确定的属性名进行类型检查
使用 TS 开发过程中,很容易碰到在获取对象属性值时,通过变量获取,这个时候,TS 又会报错了:
let valueKeys = ['value1', 'value2', 'value3']
const obj = {
value1: 'this is value',
value2: 'this is value also',
value3: 'this is value too'
}
console.log(obj[valueKeys[0]], obj[labelKey[1]])
这个时候,接口的额外属性检查就香了
interface ObjType {
[propName: string]: string;
}
let valueKeys = ['value1', 'value2', 'value3'];
const obj = {
value1: 'this is value',
value2: 'this is value also',
value3: 'this is value too'
};
console.log(obj[valueKeys[0]], obj[labelKey[1]])
额外的属性检查最适用的情况就是对不确定属性名的属性进行类型检查。