TypeScript版本: 3.6.3
搜索词: TypedPropertyDescriptor, MethodDecorator, TS2345, 属性'value'的类型不兼容。
代码
type MyDynamicDescriptor = <T>(input: T) => T
type MyStaticDescriptor = (input: number) => number
function dynamicDecorator(foo: string) {
return (_: any, __: any, descriptor: TypedPropertyDescriptor<MyDynamicDescriptor>) => {
console.log('foo:', foo)
console.log('descriptor.value:', descriptor.value)
}
}
function staticDecorator(foo: string) {
return (_: any, __: any, descriptor: TypedPropertyDescriptor<MyStaticDescriptor>) => {
console.log('foo:', foo)
console.log('descriptor.value:', descriptor.value)
}
}
class myClass {
@dynamicDecorator('bar')
myMethod(input: number): number {
return input + 42
}
@staticDecorator('bar')
myOtherMethod(input: number): number {
return input + 42
}
}
预期行为:
dynamicDecorator
和 staticDecorator
都没有编译错误。
实际行为:
dynamicDecorator
有编译错误:
error TS2345: Argument of type 'TypedPropertyDescriptor<(input: number) => Promise<number>>' is not assignable to parameter of type 'TypedPropertyDescriptor<MyDynamicDescriptor>'.
Types of property 'value' are incompatible.
Type '((input: number) => Promise<number>) | undefined' is not assignable to type 'MyDynamicDescriptor | undefined'.
Type '(input: number) => Promise<number>' is not assignable to type 'MyDynamicDescriptor'.
** playground链接**
3条答案
按热度按时间uqcuzwp81#
myMethod
不是通用标识方法。dffbzjpn2#
myMethod
should be generic as typeMyDynamicDescriptor
tag5nh1u3#
你需要更新MyDynamicDescriptor的类型以匹配myMethod方法的值类型。在这种情况下,你可以将
MyDynamicDescriptor to (input: number) => number.
更改为其他值。这将允许dynamicDecorator函数中的描述符参数接受一个具有类型(input: number) => number
的属性描述符,该类型与myMethod方法兼容。