联合类型
联合类型表示一个值可以时集中类型之一,使用 |
进行分隔每种类行。
联合类型的变量在被赋值的时候,根据类型推论的规则,推断出一个类型。
联合类型的变量当被推断出类型后,就变得和正常声明的变量一样:
let ddd: string | number; ddd = 'hello world'; // ddd被推断成了 string,访问 length 属性不会报错 console.log(ddd.length); ddd = 255; // 报错 ddd 被推断成了 number,访问 length 属性时就报错了 console.log(ddd.length);
联合类型的变量没有被推断出类型时,这个变量只能访问联合类型中所有类型共有的属性:
function func(name: string, age: string | number) { // Error,Property 'length' does not exist on type 'string | number'.Property 'length' does not exist on type 'number'. console.log(age.length); // 编译通过 console.log(age.toString()); }
交叉类型
交叉类型是将多个类型合并为一个类型,交叉类型的变量拥有所有类型的所有属性、方法,使用 &
进行合并类型:
function extend<T, U>(first: T, second: U): T & U { const result = <T & U>{}; for (let id in first) { (<T>result)[id] = first[id]; } for (let id in second) { if (!result.hasOwnProperty(id)) { (<U>result)[id] = second[id]; } } return result; } const x = extend({ a: 'hello' }, { b: 42 }); // 现在 x 拥有了 a 属性与 b 属性 const a = x.a; const b = x.b;