{let str: string = 'this is string';let num: number = 1;let bool: boolean = true;}{const str: string = 'this is string';const num: number = 1;const bool: boolean = true;}
看着上面的示例,可能你已经在嘀咕了:定义基础类型的变量都需要写明类型注解,TypeScript 太麻烦了吧?在示例中,使用 let 定义变量时,我们写明类型注解也就罢了,毕竟值可能会被改变。可是,使用 const 常量时还需要写明类型注解,那可真的很麻烦。
实际上,TypeScript 早就考虑到了这么简单而明显的问题。
在很多情况下,TypeScript 会根据上下文环境自动推断出变量的类型,无须我们再写明类型注解。因此,上面的示例可以简化为如下所示内容:
let 推断为 基本类型
const 推断为字面量类型
{let str = 'this is string'; // => let str:string = 'this is string';let num = 1; // 等价 => let num:number = 1;let bool = true; // 等价 => let bool:boolean = true;}{const str = 'this is string'; // => const str:'this is string' = 'this is string'const num = 1; // => const num:1 = 1const bool = true; //=> const bool:true = true}
我们把 TypeScript 这种基于赋值表达式推断类型的能力称之为类型推断。
在 TypeScript 中,具有初始化值的变量、有默认值的函数参数、函数返回的类型都可以根据上下文推断出来。比如我们能根据 return 语句推断函数返回的类型,如下代码所示:
{/** 根据参数的类型,推断出返回值的类型也是 number */function add1(a: number, b: number) {return a + b;}const x1= add1(1, 1); // 推断出 x1 的类型也是 number/** 推断参数 b 的类型是数字或者 undefined,返回值的类型也是数字 */function add2(a: number, b = 1) {return a + b;}const x2 = add2(1);const x3 = add2(1, '1'); // ts(2345) Argument of type "1" is not assignable to parameter of type 'number | undefined}
如果定义的时候没有赋值,不管之后有没有赋值,都会被推断成 any 类型而完全不被类型检查
let myFavoriteNumber;myFavoriteNumber = 'seven';myFavoriteNumber = 7;
如果定义的时候没有赋值,不管之后有没有赋值,都会被推断成 any 类型而完全不被类型检查:
let myFavoriteNumber;myFavoriteNumber = 'seven';myFavoriteNumber = 7;
