我正在尝试将一些逻辑移至抽象类。 考虑具有以下约束的抽象泛型类:
abstract class AbstractVersion<
TModel extends object,
TProperty extends keyof TModel,
TValue = TModel[TProperty]> {
private _version: TValue;
public get version(): TValue {
return this._version;
}
}
因此,可以通过示例进行扩展
class MyVersionedModel extends AbstractVersion<MyModel, 'MyNumericId'>
到目前为止,太好了。但是现在我想将TProperty类型用作值,这样可能吗?
abstract class AbstractVersion<
TModel extends object,
TProperty extends keyof TModel,
TValue = TModel[TProperty]> {
private _version: TValue;
public get version(): TValue {
return this._version;
}
set(model: TModel): void {
this._version = model[TProperty];
}
apply(fx: (property: string, value: TValue) => boolean): boolean {
return fx(TProperty.toString(), this.version);
}
}
所以很明显我收到语法错误'TProperty' only refers to a type, but is being used as a value here.
在model[TProperty]
和TProperty.toString()
上,但是是否可以将TProperty作为值访问?
答案 0 :(得分:0)
这是不可能的,因为在运行时您的所有键入都不可用。请记住,Typescript被编译为JavaScript,而JavaScript不了解类型。
我认为您需要在某个地方指定有效的密钥,因为注释中建议使用构造函数作为最佳参数。