类型注解

布尔值 boolean

let isDone: boolean = false;

数字 number

let decLiteral: number = 6; // 十进制
let hexLiteral: number = 0xf00d; // 十六进制
let binaryLiteral: number = 0b1010; // 二级制
let octalLiteral: number = 0o744; // 八进制

字符串 string

let myName: string = "bob";
myName = "smith";

let sentence: string = `Hello, my name is ${ myName }.

任意类型 any

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
let obj: {
  num: string,
  toString: () => void
} = {
  num: '123',
  toString: function() {}
}
// 在获取 obj. 时,就会有提示,说 obj 下边有 num、toString 两个属性

let obj: any = {
  num: '123',
  toString: function() {}
} // 改为 any 后,获取 obj. 时就没有提示了
let list: any[] = [1, true, "free"];

list[1] = 100;
let a;
a = '123';
a = 123;

Untitled

void