我可以在编译时通过装饰器将 属性 添加到 class 吗?
Can I add a property to a class at compile time via a decorator?
我有以下代码
export class TestClass {
query<TId, TRequest extends TId, TResponse extends TId>(request: TRequest) : TResponse {
return null;
}
test() {
let request = new SomeQuery1();
let response = this.query<{ "a b c" }, SomeQuery1, SomeResponse1>(request);
}
}
class SomeQuery1 {
public "a b c": string;
}
class SomeResponse1 {
public "a b c": string;
}
"a b c" 位只是我正在使用的一个标记,它让通用约束知道这两个 类 在某种程度上是相关的。我打算使用一个唯一的名称。但无论如何,我想做的是这个
@myDecorator("a b c")
class SomeQuery1 {
}
@myDecorator("a b c")
class SomeResponse1 {
}
//Is effectively the same as this
class SomeQuery1 {
public "a b c": string;
}
class SomeResponse1 {
public "a b c": string;
}
所以原来的 TestClass
仍然会在编译时使用相同的强类型检查。使用装饰器或任何其他 TypeScript 机制是否可能?
装饰器并不是为了改变 class 原型而设计的。
有一个 request in the official TypeScript repository 支持通过装饰器改变 classes。
目前,您可以使用装饰器使用 reflect-metadata 添加元数据。然后您可以在运行时验证 class 是否具有该元数据,并在需要但缺失时抛出异常。
我有以下代码
export class TestClass {
query<TId, TRequest extends TId, TResponse extends TId>(request: TRequest) : TResponse {
return null;
}
test() {
let request = new SomeQuery1();
let response = this.query<{ "a b c" }, SomeQuery1, SomeResponse1>(request);
}
}
class SomeQuery1 {
public "a b c": string;
}
class SomeResponse1 {
public "a b c": string;
}
"a b c" 位只是我正在使用的一个标记,它让通用约束知道这两个 类 在某种程度上是相关的。我打算使用一个唯一的名称。但无论如何,我想做的是这个
@myDecorator("a b c")
class SomeQuery1 {
}
@myDecorator("a b c")
class SomeResponse1 {
}
//Is effectively the same as this
class SomeQuery1 {
public "a b c": string;
}
class SomeResponse1 {
public "a b c": string;
}
所以原来的 TestClass
仍然会在编译时使用相同的强类型检查。使用装饰器或任何其他 TypeScript 机制是否可能?
装饰器并不是为了改变 class 原型而设计的。
有一个 request in the official TypeScript repository 支持通过装饰器改变 classes。
目前,您可以使用装饰器使用 reflect-metadata 添加元数据。然后您可以在运行时验证 class 是否具有该元数据,并在需要但缺失时抛出异常。