interfacePerson { name: string age: number location: string }
typeK1 = keyof Person// "name" | "age" | "location" typeK2 = keyof Person[] // number | "length" | "push" | "concat" | ... typeK3 = keyof { [x: string]: Person } // string | number console.log(K1) 'K1' only refers to a type, but is being used as a value here. console.log(Person)
'Person' only refers to a type, but is being used as a value here. 说明类型是不能作为值打印出来
enumDifficulty { Easy, Intermediate, Hard }
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key] }
new C // 可选的类型参数 new C ( ... ) // 可选的参数列表 new C < ... > ( ... ) // 可选的类型注解
6.1 构造函数类型
包含一个或多个构造签名的对象类型被称为构造函数类型;
构造函数类型可以使用「构造函数类型字面量」或包含「构造签名」的对象类型字面量来编写。
构造函数类型字面量 👇:
new < T1, T2, ... > ( p1, p2, ... ) => R
与「对象类型字面量」是等价的:
{ new < T1, T2, ... > ( p1, p2, ... ) : R }
举个实际的示例:
// 「构造函数类型字面量」 new (x: number, y: number) => Point
等价于:「对象类型字面量」
{ new (x: number, y: number): Point }
6.2 构造函数类型的应用
切换 ⇩
interfacePoint { new (x: number, y: number): Point x: number y: number }
classPoint2DimplementsPoint { readonlyx: number readonlyy: number
constructor(x: number, y: number) { this.x = x this.y = y } }
constpoint: Point = newPoint2D(1, 2) // 抛错: // Class 'Point2D' incorrectly implements interface 'Point'. // Type 'Point2D' provides no match for the signature 'new (x: number, y: number): Point'.
要解决这个问题,我们就需要把对前面定义的 Point 接口进行分离,即把接口的属性和构造函数类型进行分离:
interfacePoint { x: number; y: number; }
interfacePointConstructor { new (x: number, y: number): Point; }
完成接口拆分之后,除了前面已经定义的 Point2D 类之外,我们又定义了一个 newPoint 工厂函数,该函数用于根据传入的 PointConstructor 类型的构造函数,来创建对应的 Point 对象。
切换 ⇩
classPoint2DimplementsPoint { readonlyx: number readonlyy: number;