明确赋值断言

明确赋值断言是一项功能,它允许将!放置在实例属性和变量声明之后,来表明此属性已经确定它已经被赋值了

  1. let x: number;
  2. initialize();
  3. console.log(x + x); // 在赋值前使用了变量“x”。ts(2454)
  4. function initialize() {
  5. x = 10;
  6. }

上面的例子就很棘手,我们明明已经间接地赋值了,但是它依然报错,因此我们 let x!: number 来修复此问题,同样也可以在表达式中直接使用:

  1. let x: number;
  2. initialize();
  3. console.log(x! + x!); //ok
  4. function initialize() {
  5. x = 10;
  6. }

is关键字

  1. function isString(test: any): test is string{
  2. return typeof test === 'string';
  3. }
  4. function example(foo: number | string){
  5. if(isString(foo)){
  6. console.log(foo.length); // string function
  7. }
  8. }
  9. example('hello world');

test is string 的作用就是判断test是不是string类型,并根据结果返回boolean 相关类型
is 为关键字的「类型谓语」把参数的类型范围缩小了,当使用了 test is string 之后,我们通过 isString(foo) === true 明确知道其中的参数是 string,而 boolean 并没有这个能力,这就是 is 关键字存在的意义.

typeof关键字

可以帮助ts判断出变量的基本类型

  1. function fn (x: string | number) {
  2. if (typeof x === 'string') { // x is string
  3. return x.length
  4. } else { // x is number ts自定会判断是number类型
  5. // .....
  6. }
  7. }

typeof关键词除了可以做类型保护,还可以从实现推断出类型
此时的 typeof 是一个类型关键词,只可以用在类型语法中

  1. function fn(x:string){
  2. return x.length
  3. }
  4. const obj = {
  5. x:1,
  6. y:'2'
  7. }
  8. type T1 = typeof fn // (x: string) => number
  9. type T2 = typeof obj // {x: number; y: string }

null 和undefined的类型保护

在条件判断中,ts会自动对null和undefined进行类型保护

  1. function fn(x?:string){
  2. if(x){
  3. return x.length
  4. }
  5. }
  6. function fn(x?:string){
  7. return x!.length
  8. }

如果我们明确知道参数类型不为空,可以使用!来手动标记