Typescript 将KeysOfType与泛型一起使用
我们根据这篇文章创建了以下类型: 导出类型KeysOfType={[P in keyof T]:T[P]扩展TProp?P:never}[keyof T]; 在这个例子中Typescript 将KeysOfType与泛型一起使用,typescript,typescript-typings,Typescript,Typescript Typings,我们根据这篇文章创建了以下类型: 导出类型KeysOfType={[P in keyof T]:T[P]扩展TProp?P:never}[keyof T]; 在这个例子中 class A { public prop1: number; public prop2: string; public prop3: string; } class B<O extends A> { private prop: KeysOfType<O, string>;
class A {
public prop1: number;
public prop2: string;
public prop3: string;
}
class B<O extends A>
{
private prop: KeysOfType<O, string>;
private prop2: KeysOfType<A, string>;
public method(): void
{
let o: O;
let notTypedAsString = o[this.prop];
let a: A;
let typedAsString = a[this.prop2];
}
}
A类{
公共物品1:数量;
公共prop2:字符串;
公共prop3:字符串;
}
B类
{
私有属性:KeysOfType;
私有prop2:KeysOfType
有没有办法让它起作用?你引用的答案(被引用总是很好:))适用于使用站点。因此,当您使用使用KeysOfType
的类或函数时,您将获得预期的行为。问题是,在泛型类型未知的类或函数中,typescript无法解释索引操作将产生什么
我们可以使用类似的方法。其中,泛型参数本身扩展了仅具有字符串键(Record
)的内容。我们将需要一个额外的参数K
,以仅捕获O
类型的字符串键,但这一切都按预期工作:
export type KeysOfType<T, TProp> = { [P in keyof T]: T[P] extends TProp ? P : never }[keyof T];
class A {
public prop1: number;
public prop2: string;
public prop3: string;
}
class B<O extends Record<K, string> & A, K extends string | number | symbol = KeysOfType<O, string> >
{
constructor() {
}
private prop: K;
private prop2: keyof A
public method(): void {
let o!: O;
let notTypedAsString = o[this.prop]; // if you hover over it it will be O[K]
notTypedAsString.bold();//but it behaves as string
o.prop1 // number, A memebrs that arae not strings still work as expected
}
}
new B<A>()
class A2 extends A {
public prop4: number;
public prop5: string;
}
new B<A2>()
导出类型KeysOfType={[P in keyof T]:T[P]扩展TProp?P:never}[keyof T];
甲级{
公共物品1:数量;
公共prop2:字符串;
公共prop3:字符串;
}
B类
{
构造函数(){
}
私人道具:K;
私人道具2:钥匙
public方法():void{
让o!:o;
让notTypedAsString=o[this.prop];//如果将鼠标悬停在它上面,它将是o[K]
notTypedAsString.bold();//但其行为类似于字符串
o、 prop1//number,一个不使用字符串的内存仍能按预期工作
}
}
新B()
类A2扩展了{
公共物品4:数量;
公共道具5:字符串;
}
新B()
我认为你要求编译器太聪明了。当O
是泛型时,它倾向于将O[K]
或keyof O
等类型的求值推迟到指定O
之后。因此编译器面临O[keyof type]
并没有足够的智能将其简化为字符串的子类型(想想你如何编写编译器,以注意到会导致严重的性能损失)。类B
和直接使用keyof O
将起作用,但它不会强制执行O扩展
export type KeysOfType<T, TProp> = { [P in keyof T]: T[P] extends TProp ? P : never }[keyof T];
class A {
public prop1: number;
public prop2: string;
public prop3: string;
}
class B<O extends Record<K, string> & A, K extends string | number | symbol = KeysOfType<O, string> >
{
constructor() {
}
private prop: K;
private prop2: keyof A
public method(): void {
let o!: O;
let notTypedAsString = o[this.prop]; // if you hover over it it will be O[K]
notTypedAsString.bold();//but it behaves as string
o.prop1 // number, A memebrs that arae not strings still work as expected
}
}
new B<A>()
class A2 extends A {
public prop4: number;
public prop5: string;
}
new B<A2>()