明确赋值断言
明确赋值断言是一项功能,它允许将!放置在实例属性和变量声明之后,来表明此属性已经确定它已经被赋值了
let x: number;initialize();console.log(x + x); // 在赋值前使用了变量“x”。ts(2454)function initialize() {x = 10;}
上面的例子就很棘手,我们明明已经间接地赋值了,但是它依然报错,因此我们 let x!: number 来修复此问题,同样也可以在表达式中直接使用:
let x: number;initialize();console.log(x! + x!); //okfunction initialize() {x = 10;}
is关键字
function isString(test: any): test is string{return typeof test === 'string';}function example(foo: number | string){if(isString(foo)){console.log(foo.length); // string function}}example('hello world');
test is string 的作用就是判断test是不是string类型,并根据结果返回boolean 相关类型
is 为关键字的「类型谓语」把参数的类型范围缩小了,当使用了 test is string 之后,我们通过 isString(foo) === true 明确知道其中的参数是 string,而 boolean 并没有这个能力,这就是 is 关键字存在的意义.
typeof关键字
可以帮助ts判断出变量的基本类型
function fn (x: string | number) {if (typeof x === 'string') { // x is stringreturn x.length} else { // x is number ts自定会判断是number类型// .....}}
typeof关键词除了可以做类型保护,还可以从实现推断出类型
此时的 typeof 是一个类型关键词,只可以用在类型语法中
function fn(x:string){return x.length}const obj = {x:1,y:'2'}type T1 = typeof fn // (x: string) => numbertype T2 = typeof obj // {x: number; y: string }
null 和undefined的类型保护
在条件判断中,ts会自动对null和undefined进行类型保护
function fn(x?:string){if(x){return x.length}}function fn(x?:string){return x!.length}
如果我们明确知道参数类型不为空,可以使用!来手动标记
