Reputation: 81
Since there is TypedPropertyDescriptor which can be used to define method decorators, is there any way to let the compiler to infer parameter types of decorated methods?
function test(
target: any,
propName: string | symbol,
descriptor: TypedPropertyDescriptor<(x: number) => any>
) {
}
class T {
@test
log(n) { // <-- compiler complains that n has type of implicit any
}
}
As (x: number) => any
was passed into TypedPropertyDescriptor
, it implies that all methods decorated by test
should be of type (x: number) => any
, thus above code should type check.
So TypeScript doesn't support this kind of inference yet, or do I miss something which could make this code type check?
Upvotes: 1
Views: 936
Reputation: 250922
There are many cases where TypeScript undertakes contextual typing, but this isn't one.
Add the type annotation to the parameter:
class T {
@test
log(n: number) {
}
}
The type is still checked in relation to the decorator, even though the decorator does not provide contextual type information:
class T {
@test
log(n: string) { // ERROR!
}
}
Upvotes: 4