Почему ts пишет что реализация фуцнкции не совпадает с ее типом?
Описал тип функции как написано в документации typescript doc
При написании реализации функции TS почему то пишет что типы не совпадают. Скажите пожалуйста - где я ошибся ?
type PropertyFuncType = {
(a: number): number;
apply(this: Function, thisArg: any, argArray?: any): any;
};
// type PropertyFuncType = Function;
function Method2(): MethodDecorator {
return <PropertyFuncType>(
target: Object,
propertyKey: string | symbol,
propertyDescriptor: TypedPropertyDescriptor<PropertyFuncType>
) => {
const oldValue: PropertyFuncType = propertyDescriptor.value!;
// Type '(a: number) => number' is not assignable to type 'PropertyFuncType'.
// 'PropertyFuncType' could be instantiated with an arbitrary type which could be unrelated to '(a: number) => number'.(2322)
// сам тип функции я описал как в документации:
// https://www.typescriptlang.org/docs/handbook/2/functions.html#call-signatures
propertyDescriptor.value = function (a: number): number {
// Подскажите пожалуйста, почему TS пишет что типы не совпадают ?
// Property 'apply' does not exist on type 'PropertyFuncType' - я же apply сам в тип записал ?
const result: number = oldValue.apply(this, a);
return result * 10;
};
};
}
Ссылка на playground: typescript playground
Ответы (1 шт):
Автор решения: Трипольский Пётр
→ Ссылка
Попробуйте использовать следующий код
Ссылка на пример доступна в gist
import 'reflect-metadata';
function Method2(): MethodDecorator {
return function (target, propertyKey): PropertyDescriptor {
const descriptor = Reflect.getOwnPropertyDescriptor(target, propertyKey)!;
return {
...descriptor,
value() {
return descriptor.value?.apply(target, arguments) * 10;
},
};
};
}
class Test {
@Method2()
applyTest() {
return 10;
}
}
const test = new Test();
const result1 = test.applyTest();
console.log(result1);