从更抽象类型继承的特定类型
Specific types that inherit from more abstract types
我是 Typescript 的新手,如果这很明显,我深表歉意。
我有一个 class 和一个与之关联的类型,如下所示。
interface childType {
a: string;
b: string;
}
class Child extends Parent {
instanceVar: childType
}
此 class 从父级扩展。
在父级中,instanceVar 的类型为 Record。
有一个名为 getValues 的函数枚举该 Record 和 returns 一个字符串数组
class Parent {
instanceVar: Record<string, string>
constructor(iV: Record<string, string>) {
this.instanceVar = iV;
}
getAllValues = (): Array<string> =>{
let values : Array<string> = [];
Object.keys(this.instanceVar).forEach((key) => {
let val = this.instanceVar[key];
values.push(val);
})
return values;
}
}
这目前不起作用,typescript 抱怨子对象中的 instanceVar 与父对象的类型不同。然而对我来说,这是因为“childType”基本上是一个 Record(字符串映射到字符串),但更“具体”。
我知道我可以用泛型解决类型错误,但我的真正目标是不必覆盖子 class 中的 getValues 函数。我想在父 class 中编写一次 getValues,并将其应用于所有子 classes。这意味着子 classes 中的 instanceVar 以某种方式从 Record 类型“继承”了它的类型。
无需在子项中重新定义 instanceVar
,您可以将其设为父项的通用参数。这还需要对 Object.keys
的值进行类型断言,因为默认情况下 Typescript 的类型比您想要的更广泛,但这是非常标准的。尝试:
class Parent<T extends Record<keyof T, string>> {
instanceVar: T
constructor(iV: T) {
this.instanceVar = iV;
}
getAllValues = (): Array<string> =>{
let values : Array<string> = [];
const keys = Object.keys(this.instanceVar) as (keyof T)[] // <-- type assertion
keys.forEach((key) => {
let val = this.instanceVar[key];
values.push(val);
})
return values;
}
}
interface childType {
a: string;
b: string;
}
class Child extends Parent<childType> {
}
我是 Typescript 的新手,如果这很明显,我深表歉意。 我有一个 class 和一个与之关联的类型,如下所示。
interface childType {
a: string;
b: string;
}
class Child extends Parent {
instanceVar: childType
}
此 class 从父级扩展。
在父级中,instanceVar 的类型为 Record
class Parent {
instanceVar: Record<string, string>
constructor(iV: Record<string, string>) {
this.instanceVar = iV;
}
getAllValues = (): Array<string> =>{
let values : Array<string> = [];
Object.keys(this.instanceVar).forEach((key) => {
let val = this.instanceVar[key];
values.push(val);
})
return values;
}
}
这目前不起作用,typescript 抱怨子对象中的 instanceVar 与父对象的类型不同。然而对我来说,这是因为“childType”基本上是一个 Record(字符串映射到字符串),但更“具体”。
我知道我可以用泛型解决类型错误,但我的真正目标是不必覆盖子 class 中的 getValues 函数。我想在父 class 中编写一次 getValues,并将其应用于所有子 classes。这意味着子 classes 中的 instanceVar 以某种方式从 Record 类型“继承”了它的类型。
无需在子项中重新定义 instanceVar
,您可以将其设为父项的通用参数。这还需要对 Object.keys
的值进行类型断言,因为默认情况下 Typescript 的类型比您想要的更广泛,但这是非常标准的。尝试:
class Parent<T extends Record<keyof T, string>> {
instanceVar: T
constructor(iV: T) {
this.instanceVar = iV;
}
getAllValues = (): Array<string> =>{
let values : Array<string> = [];
const keys = Object.keys(this.instanceVar) as (keyof T)[] // <-- type assertion
keys.forEach((key) => {
let val = this.instanceVar[key];
values.push(val);
})
return values;
}
}
interface childType {
a: string;
b: string;
}
class Child extends Parent<childType> {
}