【发布时间】:2019-09-26 08:36:22
【问题描述】:
我有一个泛型类,它接受另一种类型和这种类型的键名。我还想用这个键名初始化属性。我已经在 TS 中定义了这个,但我必须明确地将键的名称作为通用参数传递,并将相同的值传递给构造函数。它看起来有点不必要 - 这些值总是相同的(类型和值)。
是否可以从其构造函数参数推断泛型类的类型?或者使用通用“类型”作为“值”(可能不是 - 我有错误:'ValueKey' only refers to a type, but is being used as a value here.ts(2693))。
带定义的代码:
interface InterfaceWithProperties {
stringProperty: string;
numberProperty: number;
}
class GenericCLass<TypeWithKeys, ExactKey extends keyof TypeWithKeys> {
keyNameFromAnotherType: ExactKey; // this property should have value equal to key from another type;
// is it a way to remove this parameter? it's exactly duplicated with ExactKey
// or to detect correctly ExactKey type based on `property` value
constructor(keyNameFromAnotherType: ExactKey) {
// this.property = ExactKey; // ofc: not working code
this.keyNameFromAnotherType = keyNameFromAnotherType;
}
}
当前使用情况:
const test1 = new GenericCLass<InterfaceWithProperties, 'stringProperty'>('stringProperty');
我想要相同的结果,但没有这个额外的参数。像这样的:
const test2 = new GenericCLass<InterfaceWithProperties, 'stringProperty'>();
或者像这样:
const test3 = new GenericCLass<InterfaceWithProperties>('stringProperty');
带有此代码的 TS 游乐场:link
【问题讨论】:
标签: typescript typescript-generics