1. {
    2. let str: string = 'this is string';
    3. let num: number = 1;
    4. let bool: boolean = true;
    5. }
    6. {
    7. const str: string = 'this is string';
    8. const num: number = 1;
    9. const bool: boolean = true;
    10. }

    看着上面的示例,可能你已经在嘀咕了:定义基础类型的变量都需要写明类型注解,TypeScript 太麻烦了吧?在示例中,使用 let 定义变量时,我们写明类型注解也就罢了,毕竟值可能会被改变。可是,使用 const 常量时还需要写明类型注解,那可真的很麻烦。
    实际上,TypeScript 早就考虑到了这么简单而明显的问题。
    在很多情况下,TypeScript 会根据上下文环境自动推断出变量的类型,无须我们再写明类型注解。因此,上面的示例可以简化为如下所示内容:
    let 推断为 基本类型
    const 推断为字面量类型

    1. {
    2. let str = 'this is string'; // => let str:string = 'this is string';
    3. let num = 1; // 等价 => let num:number = 1;
    4. let bool = true; // 等价 => let bool:boolean = true;
    5. }
    6. {
    7. const str = 'this is string'; // => const str:'this is string' = 'this is string'
    8. const num = 1; // => const num:1 = 1
    9. const bool = true; //=> const bool:true = true
    10. }

    我们把 TypeScript 这种基于赋值表达式推断类型的能力称之为类型推断。
    在 TypeScript 中,具有初始化值的变量、有默认值的函数参数、函数返回的类型都可以根据上下文推断出来。比如我们能根据 return 语句推断函数返回的类型,如下代码所示:

    1. {
    2. /** 根据参数的类型,推断出返回值的类型也是 number */
    3. function add1(a: number, b: number) {
    4. return a + b;
    5. }
    6. const x1= add1(1, 1); // 推断出 x1 的类型也是 number
    7. /** 推断参数 b 的类型是数字或者 undefined,返回值的类型也是数字 */
    8. function add2(a: number, b = 1) {
    9. return a + b;
    10. }
    11. const x2 = add2(1);
    12. const x3 = add2(1, '1'); // ts(2345) Argument of type "1" is not assignable to parameter of type 'number | undefined
    13. }

    如果定义的时候没有赋值,不管之后有没有赋值,都会被推断成 any 类型而完全不被类型检查

    1. let myFavoriteNumber;
    2. myFavoriteNumber = 'seven';
    3. myFavoriteNumber = 7;

    如果定义的时候没有赋值,不管之后有没有赋值,都会被推断成 any 类型而完全不被类型检查:

    1. let myFavoriteNumber;
    2. myFavoriteNumber = 'seven';
    3. myFavoriteNumber = 7;