interface Animal { name:string } interface Dog extends Animal { breed:string; } interface NotOkay { [x:number]:Animal; [x:string]:Dog; //error TS2413: 'number' index type 'Animal' is not assignable to 'string' index type 'Dog'. }
functiondraw(circle:Colorful&Circle){ console.log(`Color was ${circle.color}`); console.log(`Radius was ${circle.radius}`); } // okay draw({ color: "blue", radius: 42 }); // oops draw({ color: "red", raidus: 42 }); // Argument of type '{ color: string; raidus: number; }' is not assignable to parameter of type 'Colorful & Circle'. // Object literal may only specify known properties, but 'raidus' does not exist in type 'Colorful & Circle'. Did you mean to write 'radius'?
接口继承和交叉类型
区别在于冲突怎么处理,这也是选择要使用哪种方式的主要原因
1 2 3 4 5 6 7 8 9
interface Colorful { color:string; } interface ColorfulSub extends Colorful { color:number; } // Interface 'ColorfulSub' incorrectly extends interface 'Colorful'. // Types of property 'color' are incompatible. // Type 'number' is not assignable to type 'string'.
使用继承方式,如果重写类型会导致编译错误,但交叉类型不会
1 2 3 4 5 6
interface Colorful { color:string; } type ColorfulSub=Colorful&{ color:number }
不报错,color属性的类型是nerver,取得的是string和number的交集
类型别名和接口:
类型别名不同于接口,可以描述的不止是对象类型,我们也可以用类型别名写一些其他种类的泛型帮助类型
1 2 3 4 5 6 7 8 9 10 11
type OrNull<Type> = Type | null; type OneOrMany<Type> = Type | Type[]; type OneOrManyOrNull<Type> = OrNull<OneOrMany<Type>>; type OneOrManyOrNull<Type> = OneOrMany<Type> | null type OneOrManyOrNullStrings = OneOrManyOrNull<string>; type OneOrManyOrNullStrings = OneOrMany<string> | null
元组类型在重度依赖约定的 API 中很有用,因为它会让每个元素的意义都很明显。当我们解构的时候,元组给了我们命名变量的自由度。
元组类型中,可以写一个可选属性,但可选元素必须在最后面,而且会影响类型的length
1 2 3 4 5 6 7 8
type Either2dOr3d=[number,number,number?]; functionsetCoordinate(coord:Either2dOr3d){ const [x,y,z]=coord; //const z:number|undefined console.log(`Provided coordinates had ${coord.length} dismensions`); //(property) length:2|3 }
Tuples可以使用剩余元素语法,但必须是array/tuple类型:
1 2 3
type StringNumberBooleans=[string,number,...boolean[]]; type StringBooleansNumber = [string, ...boolean[], number]; type BooleansStringNumber = [...boolean[], string, number];
let point=[3,4] asconst; functiondistanceFromOrigin([x,y]:[number,number]){ returnMath.sqrt(x**2+y**2); } distanceFromOrigin(point); // Argument of type 'readonly [3, 4]' is not assignable to parameter of type '[number, number]'. // The type 'readonly [3, 4]' is 'readonly' and cannot be assigned to the mutable type '[number, number]'.