简体   繁体   中英

Why can't Typescript infer the argument types of this function?

Say we have this type declaration:

declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;

If we define a method which states this to be this type, why can't typescript deduce the types of the arguments?

const fetchJson: MethodDecorator = (target, propertyKey, descriptor) => {
    ...
}

Typescripts infer the arguments as having the any type. Why is this?

Contextual typing of function expressions does not occur when the contextual type's signature is generic. This is because it would cause the type parameter type to "leak out", which is a big no-no -- you should never be able to see an unspecified type parameter T outside the declaration in which it was declared.

You could fix this by moving the type parameter to the type instead of being on the signature :

type SomeMethodDecorator<T> = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;

let x: SomeMethodDecorator<string> = (a, b, c) => {
    // a: Object, etc.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM