あなたは試みることができる:
interface Newable<T> {
new (...args: any[]): T;
}
function decorate()
{
return function (target: Newable<Object>)
{
return class myExtendClass extends target {
public someOtherProp: string;
publicconstructor() {
this.someOtherProp = "test2";
}
}
};
};
をしかし、その後、あなたは新しいエラーが発生します。
// Error: Type 'typeof myExtendClass' is
// not assignable to type 'typeof Something'.
@decorate()
class Something{
public someProp: string;
publicconstructor() {
this.someProp = "test";
}
}
あなたはそれを修正しようとすることができます:
あなたが得る
function decorate()
{
return function (target: Newable<Object>)
{
class myExtendClass extends target {
public someOtherProp: string;
publicconstructor() {
this.someOtherProp = "test2";
}
}
return (<any>myExtendClass); // notice casting!
};
};
そして再び別のエラー:
let something = new Something();
console.log(something.someProp);
// Property 'someOtherProp' does not
//exist on type 'Something'.
console.log(something.someOtherProp);
最後に、あなたがいずれかにキャストすることによって、それを解決することができ:もちろん
console.log((<any>something).someOtherProp); // More casting!
これは理想的なソリューションではありません。私の代わりに、次のような何かを行うしようとするだろう。
interface Newable<T> {
new (...args: any[]): T;
}
function decorate()
{
return function (target: Newable<Object>)
{
class myExtendClass extends target {
public someOtherProp: string;
publicconstructor() {
this.someOtherProp = "test2";
}
}
return (<any>myExtendClass);
};
};
function applyDecorator<T,TDecorated>(decorator, ctr): Newable<TDecorated> {
// Decorators are just functions, you don't need @ symbol to use them :)
let decorated: Newable<TDecorated> = <any>decorator()(ctr);
}
interface ISomething {
someProp: string;
}
interface ISomethingElse extends Something {
someOtherProp: string;
}
class Something implements ISomething {
public someProp: string;
publicconstructor() {
this.someProp = "test";
}
}
let SomethingElse = applyDecorator<ISomething, ISomethingElse>(decorate, Something);
let something = new SomethingElse();
console.log(something.someProp);
console.log(something.someOtherProp);
はそれが役に立てば幸い:)
を参照してください。多分Function' 'に' any'を変更してみてください? http://stackoverflow.com/questions/29775830/how-to-implement-a-typescript-decoratorおよびhttps://blogs.msdn.microsoft.com/typescript/2015/04/30の「クラスデコレータ」を確認してください。/announceus-typescript-1-5-beta/ –
@SayanPalはすでにFunctionを試していて、動作していません。私はそれが有効なTSコードでなければならないので、Reflect APIを使用しなければならないのがちょっと変わっています:) –
あなたの例でクラスを拡張するためにデコレータを使用しようとしています。ここの主な問題?または、あなたの質問はちょうどデコレータを働かせることについてですか? – Alex