タイプスクリプトハンドブックには、クラスデコレータを使用してコンストラクタをオーバーライドする方法の例があります(リンク)。
function classDecorator<T extends { new (...args: any[]): {} }>(
constructor: T
) {
return class extends constructor {
newProperty = "new property";
hello = "override";
};
}
@classDecorator
class Greeter {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
}
結果のクラスのインスタンスをログアウトすると、クラス名が見つかりません。
console.log(new Greeter("world"));
//=> { "property": "property", "hello": "override", "newProperty": "new property" }
ここで、デコレータを変更して新しいクラスを変数に割り当てると、ログにはその変数の名前が含まれます。
function classDecorator2<T extends { new (...args: any[]): {} }>(
constructor: T
) {
const MyDecoratedClass = class extends constructor {
newProperty = "new property";
hello = "override";
};
return MyDecoratedClass
}
@classDecorator2
class Greeter2 {
// ... same as Greeter
}
console.log(new Greeter2("world"));
//=> MyDecoratedClass: { "property": "property", "hello": "override", "newProperty": "new property" }
コンソール出力でクラスの元の名前を保持する方法はありますか?たとえば、最後のコンソールステートメントの出力を
Greeter2: { "property": "property", "hello": "override", "newProperty": "new property" }
あなたはこのようなことを試すことができますが、少しハッキーなようです。
function classDecorator<T extends { new (...args: any[]): {} }>(
constructor: T
) {
const cls = class extends constructor {
newProperty = "new property";
hello = "override";
};
Object.defineProperty(cls, 'name', {
get: () => `${constructor.name}Generated`
});
return cls
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加