@xxx("xxx") class A{ msg:string constructor(msg:string) { this.msg = msg } print() { console.log(this.msg) } } function xxx(arg:string) { function f(target) { function ff(msg: string) { return new target(arg + ":" + msg) } return ff } return f } let a = new A("hellow") a.print()
When compile, it reports:
decorator.ts(1,1): error TS1238: Unable to resolve signature of class decorator when called as an expression. Type '(msg: string) => any' is not assignable to type 'void'.
But the genrated js executed well. I don't know why report error.
Decorators are a stage 2 proposal for JavaScript and are available as an experimental feature of TypeScript. NOTE Decorators are an experimental feature that may change in future releases.
Typescript Class Decorators Definition: The class decorator is applied to the constructor of the class and can be used to observe, modify, or replace a class definition.(reference)
In TypeScript, you can create decorators using the special syntax @expression , where expression is a function that will be called automatically during runtime with details about the target of the decorator. The target of a decorator depends on where you add them.
JavaScript decorators are a relatively new feature in JavaScript that allows adding new behavior to existing functions and objects without modifying their underlying code. You can achieve it by using a special syntax that uses an @ symbol before the function name or object key.
The compiler expects your decorator to either be void or return a value that is compatible with A. It sees that you return a (msg:any) => any
but can not draw the conclusion that this function is compatible with A.
If you want to get rid of the error, you can cast the ff to any when you return it, or maybe even to typeof A
to communicate the intention clearer:
function xxx(arg: string) { function f(target) { function ff(msg: string) { return new target(arg + ":" + msg) } return <typeof A><any>ff } return f }
That said, it's probably not a good idea to replace classes like this, you should at least maintain the constructor:
TypeScript documentation:
NOTE Should you chose to return a new constructor function, you must take care to maintain the original prototype. The logic that applies decorators at runtime will not do this for you.
This appears to be resolved by adding ES2016 or ES5 as the target in tsconfig.json
https://github.com/alsatian-test/alsatian/issues/344#issuecomment-290418311
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With