值 as 类型

类型断言的用途

  • 将一个联合类型断言为其中一个类型
  • 将一个父类断言为更加具体的子类

对于ES6的class来说,使用instanceof更合适

  • 将任何一个类型断言为any

需要注意的是,将一个变量断言为 any 可以说是解决 TypeScript 中类型问题的最后一个手段。
它极有可能掩盖了真正的类型错误,所以如果不是非常确定,就不要使用 as any

  • 将any断言为一个具体的类型

    类型断言的限制

    类型断言只能够「欺骗」TypeScript 编译器,无法避免运行时的错误,反而滥用类型断言可能会导致运行时错误
    TypeScript 是结构类型系统,类型之间的对比只会比较它们最终的结构,而会忽略它们定义时的关系,若 A 兼容 B,那么 A 能够被断言为 B,B 也能被断言为 A。联想接口的extends

    双重断言

    let A as any as B
    除非迫不得已,千万别用双重断言。

    类型断言 vs 类型转换

    类型断言不是类型转换,不会真的影响到变量的类型,要进行类型转换,还需要调用js的相关转换函数

    类型断言 vs 类型声明

    类型声明比类型断言更严格 ```typescript interface Animal { name: string; } interface Cat { name: string; run(): void; }

const animal: Animal = { name: ‘tom’ }; let tom = animal as Cat;

  1. ```typescript
  2. interface Animal {
  3. name: string;
  4. }
  5. interface Cat {
  6. name: string;
  7. run(): void;
  8. }
  9. const animal: Animal = {
  10. name: 'tom'
  11. };
  12. let tom: Cat = animal; //不能将父类的实例赋值给类型为子类的变量
  13. // index.ts:12:5 - error TS2741: Property 'run' is missing in type 'Animal' but required in type 'Cat'.

深入的讲,它们的核心区别就在于:

  • animal 断言为 Cat,只需要满足 Animal 兼容 Cat 或 Cat 兼容 Animal 即可
  • animal 赋值给 tom,需要满足 Cat 兼容 Animal 才行

    类型断言 vs 泛型

    ```typescript function getCacheData(key: string): T { return (window as any).cache[key]; }

interface Cat { name: string; run(): void; }

const tom = getCacheData(‘tom’); tom.run(); ```