-
TypeScript 联合类型
联合类型(Union Types)可以通过管道(|)将变量设置多种类型,只能赋值指定的类型。
基础类型联合var val:string|number val = 12 console.log("数字为 "+ val) val = "Runoob" console.log("字符串为 " + val)
联合类型数组
var arr:number[]|string[]; var i:number; arr = [1,2,4] console.log("**数字数组**") for(i = 0;i<arr.length;i++) { console.log(arr[i]) } arr = ["Runoob","Google","Taobao"] console.log("**字符串数组**") for(i = 0;i<arr.length;i++) { console.log(arr[i]) }
对象类型联合
对象联合类型只能访问联合中所有共同成员interface Women{ age: number, sex: string, cry(): void } interface Man{ age: number, sex: string, } declare function People(): Women | Man; let people = People(); people.age = 18; //ok people.cry();//error 非共同成员
-
交叉类型 &
多种类型的集合,联合对象将具有所联合类型的所有成员interface People { age: number, height: number } interface Man{ sex: string } const lilei = (man: People & Man) => { console.log(man.age) console.log(man.height) console.log(man.sex) } lilei({age: 18,height: 180,sex: 'male'});
-
TypeScript中的泛型的理解
把类型当作是参数一样传递<数据类型>
只能是引用类型
定义泛型:
function identity<T>(arg: T): T {
return arg;
}
我们把这个版本的identity
函数叫做泛型,因为它可以适用于多个类型。
使用泛型:两种方法
第一种是,传入所有的参数,包含类型参数
let output = identity<string>("myString"); // type of output will be 'string'
第二种利用了类型推论 -- 即编译器会根据传入的参数自动地帮助我们确定T的类型
let output = identity("myString"); // type of output will be 'string'