类型声明

  • 类型声明是TypeScript中非常重要的一个特点。
  • 通过类型声明可以指定TypeScript中变量(参数,形参)的类型。
  • 指定类型后,当为变量赋值时,TS编译器会自动检查值是否符合类型声明,符合则赋值,否则报错。
  • 简而言之,类型声明给变量设置了类型,使得变量只能存储某种类型的值。
  • 语法: ```typescript let 变量: 类型; let 变量: 类型 = 值; function fn (参数: 类型, 参数: 类型): 类型 {

}

  1. <a name="rJ8wm"></a>
  2. #### 类型推论
  3. 如果没有明确的指定类型,那么TypeScript会按照类型推论的规则推断出一个类型。
  4. 下面的代码虽然没有指定类型,但是在编译的时候会报错:
  5. ```typescript
  6. let myText = 'hi';
  7. myText = 7;
  8. // index.ts(2,1): error TS2322: Type 'number' is not assignable to type 'string'.

事实上,它等价于:

  1. let myText: string = 'hi';
  2. myText = 7;
  3. // index.ts(2,1): error TS2322: Type 'number' is not assignable to type 'string'.

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

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