为什么可以';t Typescript是否推断此函数的参数类型?
假设我们有这个类型声明:为什么可以';t Typescript是否推断此函数的参数类型?,types,typescript,Types,Typescript,假设我们有这个类型声明: declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void; Typescripts推断参数具有any类型。这是为什么?当上下文类型的签名是泛型时,函数表达式的上下文类型不会
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
Typescripts推断参数具有
any
类型。这是为什么?当上下文类型的签名是泛型时,函数表达式的上下文类型不会发生。这是因为它会导致类型参数类型“漏出”,这是一个很大的禁忌——您永远不能在声明它的声明之外看到未指定的类型参数T
您可以通过将类型参数移动到类型而不是签名来解决此问题:
typesomemethoddecorator=(目标:对象,属性key:string |符号,描述符:TypedPropertyDescriptor)=>TypedPropertyDescriptor | void;
设x:SomeMethodDecorator=(a,b,c)=>{
//a:物体等。
}
如果通用签名的上下文类型有效,是否可以给出类型参数“泄漏”的示例?我相信这一切都是有道理的,我只是在想问题。
const fetchJson: MethodDecorator = (target, propertyKey, descriptor) => {
...
}
type SomeMethodDecorator<T> = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
let x: SomeMethodDecorator<string> = (a, b, c) => {
// a: Object, etc.
}