Skip to content

前言

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

什么是类型推论

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

js
let a = 1;
a = '1'

Type '"1"' is not assignable to type 'number'.

事实上等价于

js
let a: number = 1;
a = '1'

Type '"1"' is not assignable to type 'number'.

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

定义没有赋值?

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

js
ley anything;

anything = '1';
anything = 1;

测试用例

js
let debug:boolean = true;
let a = '1'; //为声明什么类型 则更具类型推论被识别为string
let b = 2;
let c = undefined;
let d = true;
let e = {
  name: 'along'
}
let f = () => {
  return true;
}

debug && console.log({
  a: typeof(a),
  b: typeof(b),
  c: typeof(c),
  d: typeof(d),
  e: typeof(e),
  f: typeof(f),
});

-----------------------------------------------------------------------------------

{
  a: 'string',
  b: 'number',
  c: 'undefined',
  d: 'boolean',
  e: 'object',
  f: 'function'
}

参考

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