Typescript:How 一般获取 class 成员的类型
Typescript:How to get type of class member generically
class Awesome<ObjType extends Object,
KeyType extends keyof ObjType ,
MemberType /* is of type obj:ObjType obj[KeyType]*/>{}
这里如何约束MemberType
作为ObjType
实例的成员类型
我想你正在寻找 MemberType extends ObjType[KeyType]
。
... typing constructs that enable static validation of code involving dynamic property names and properties selected by such dynamic names ...
— from the Pull Request that implemented the feature
对于您的代码,它是这样工作的:
class Awesome<ObjType extends Object,
KeyType extends keyof ObjType ,
MemberType extends ObjType[KeyType]> { }
interface A {
a: number;
b: string;
}
// okay:
type A1 = Awesome<A, keyof A, string | number>
// not okay:
type A2 = Awesome<A, keyof A, boolean>
// okay:
type A3 = Awesome<A, 'a', number>
type A4 = Awesome<A, 'b', string>
// not okay:
type A5 = Awesome<A, 'a', boolean>
type A6 = Awesome<A, 'b', Date>
编辑
正如 Daniel Rosenwasser 指出的那样,keyof
称为“键查询”,ObjType[KeyType]
是“索引访问类型”。
class Awesome<ObjType extends Object,
KeyType extends keyof ObjType ,
MemberType /* is of type obj:ObjType obj[KeyType]*/>{}
这里如何约束MemberType
作为ObjType
我想你正在寻找 MemberType extends ObjType[KeyType]
。
... typing constructs that enable static validation of code involving dynamic property names and properties selected by such dynamic names ...
— from the Pull Request that implemented the feature
对于您的代码,它是这样工作的:
class Awesome<ObjType extends Object,
KeyType extends keyof ObjType ,
MemberType extends ObjType[KeyType]> { }
interface A {
a: number;
b: string;
}
// okay:
type A1 = Awesome<A, keyof A, string | number>
// not okay:
type A2 = Awesome<A, keyof A, boolean>
// okay:
type A3 = Awesome<A, 'a', number>
type A4 = Awesome<A, 'b', string>
// not okay:
type A5 = Awesome<A, 'a', boolean>
type A6 = Awesome<A, 'b', Date>
编辑
正如 Daniel Rosenwasser 指出的那样,keyof
称为“键查询”,ObjType[KeyType]
是“索引访问类型”。