联合类型:
联合类型是指在定义变量时,可以通过 '|' 指定变量的类型为几种类型的联合,也就是说变量可以被赋值为几种指定类型的值:
let a: number | string;
a = 1;
console.log(a);//输出1
a = "hello";
console.log(a);//输出hello
a = true;//error TS2322: Type 'true' is not assignable to type 'string | number'.
当联合类型的变量还没有被类型推论为具体的类型时,只能访问此联合类型的所有类型里共有的属性或方法:
let a: number|string;
console.log(a.length);//输出error TS2339: Property 'length' does not exist on type 'string | number'. Property 'length' does not exist on type 'number'.
a = "hello";
console.log(a.length);//输出5
类型别名:
可以通过type为联合类型起一个别名以便于书写:
type Data = number|string;
let a : Data;
a = 1;
console.log(a);//输出1
a = "hello";
console.log(a);//输出hello
当然类型别名不限于用于联合类型,可以用于为各种类型起别名:
type Str = string;
let s : Str = 'hello';
console.log(typeof(s));//输出string