前言

在定义变量的时候,如果没有明确的指定类型,那么TypeScript根据类型推论推断出一个类型。

什么是类型推论

看下面这一段代码,虽然没有定义什么类型,但是会在编译的时候报错.

  1. let a = 1;
  2. a = '1'
  3. Type '"1"' is not assignable to type 'number'.

事实上等价于

  1. let a: number = 1;
  2. a = '1'
  3. Type '"1"' is not assignable to type 'number'.

结论:TypeScript会在没有明确指定一个类型的时候推测出一个类型,这就是类型推论。

定义没有赋值?

如果一个变量在定义的时候没有进行赋值,那么它将会被推论成任意值类型,不管后面有没有进行赋值。

  1. ley anything;
  2. anything = '1';
  3. anything = 1;

测试用例

  1. let debug:boolean = true;
  2. let a = '1'; //为声明什么类型 则更具类型推论被识别为string
  3. let b = 2;
  4. let c = undefined;
  5. let d = true;
  6. let e = {
  7. name: 'along'
  8. }
  9. let f = () => {
  10. return true;
  11. }
  12. debug && console.log({
  13. a: typeof(a),
  14. b: typeof(b),
  15. c: typeof(c),
  16. d: typeof(d),
  17. e: typeof(e),
  18. f: typeof(f),
  19. });
  20. -----------------------------------------------------------------------------------
  21. {
  22. a: 'string',
  23. b: 'number',
  24. c: 'undefined',
  25. d: 'boolean',
  26. e: 'object',
  27. f: 'function'
  28. }

参考

https://ts.xcatliu.com/basics/type-inference.html