无法从扩展 class 的类型参数访问父 class 的属性
Cannot access properties of parent class from a type parameter that extends the class
我有一个装饰器可以将一些属性添加到 class 和另一个需要第一个添加的 属性 的装饰器,例如:
// this class adds the type support
abstract class TypeDefClass {
readonly p!: number;
}
type Newable<T = any> = new (...args: any[]) => T;
const addProperties = <T extends Newable<TypeDefClass>>(target: T) => {
return class extends target {
p: number = 0;
}
}
const readProperty = <T extends Newable<TypeDefClass>>(target: T) => {
// use the target.p property
target.p // property p does not exist on T, but it should right?
}
但是如果我这样做
// though this will not applicable to a class, since it's not newable
// and will result in a type mismatch
const readProperty = (target: TypedefClass) => {
target.p; // its fine
}
我怀疑我对类型 Newable
的定义不正确,我不知道 readProperty
哪个定义是正确的。我对装饰器还很陌生,非常感谢任何帮助。
看起来是因为您没有实例化 class。
当我提取你的代码时我:
1: 注意到你拼错了 TypedefClass ;) 根据你的定义应该是 TypeDefClass :)
2: 在实例化p
属性 target
之后能够访问
如果您想静态访问它,也许可以将 p
声明为静态?
我有一个装饰器可以将一些属性添加到 class 和另一个需要第一个添加的 属性 的装饰器,例如:
// this class adds the type support
abstract class TypeDefClass {
readonly p!: number;
}
type Newable<T = any> = new (...args: any[]) => T;
const addProperties = <T extends Newable<TypeDefClass>>(target: T) => {
return class extends target {
p: number = 0;
}
}
const readProperty = <T extends Newable<TypeDefClass>>(target: T) => {
// use the target.p property
target.p // property p does not exist on T, but it should right?
}
但是如果我这样做
// though this will not applicable to a class, since it's not newable
// and will result in a type mismatch
const readProperty = (target: TypedefClass) => {
target.p; // its fine
}
我怀疑我对类型 Newable
的定义不正确,我不知道 readProperty
哪个定义是正确的。我对装饰器还很陌生,非常感谢任何帮助。
看起来是因为您没有实例化 class。
当我提取你的代码时我:
1: 注意到你拼错了 TypedefClass ;) 根据你的定义应该是 TypeDefClass :)
2: 在实例化p
属性 target
之后能够访问
如果您想静态访问它,也许可以将 p
声明为静态?