【发布时间】:2021-11-09 09:26:17
【问题描述】:
我正在尝试定义一个方法签名,其中参数应符合接口。
interface Command {}
class HelloCommand implements Command {
constructor(public readonly name: string) {}
}
type HandleCommandFn = (command: Command) => Promise<any>;
const handleHello: HandleCommandFn = (
command: HelloCommand
): Promise<string> => {
return Promise.resolve(`Hello ${command.name}`);
};
我从编译器收到以下错误:
src/index.ts:9:7 - error TS2322: Type '(command: HelloCommand) => Promise<string>' is not assignable to type 'HandleCommandFn'.
Types of parameters 'command' and 'command' are incompatible.
Property 'name' is missing in type 'Command' but required in type 'HelloCommand'.
9 const handleHello: HandleCommandFn = (
我还尝试了以下变体:
type HandleCommandFn = <C extends Command>(command: C) => Promise<any>;
type HandleCommandFn = <C extends Command = Command>(command: C) => Promise<any>;
更新
在以下答案的帮助下,我设法获得了以下代码(我的目标是定义一个类型安全的方法装饰器):
interface Command {
getDescription(): string;
}
type HandleCommandFn<C extends Command = Command> = (
command: C
) => Promise<any>;
function HandleCommand<C extends Command = Command>(
target: Object,
propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<HandleCommandFn<C>>
): void {
const method = descriptor.value;
if (method) {
// Do something
}
}
class HelloCommand implements Command {
constructor(public readonly name: string) {}
public getDescription(): string {
return "Say hello";
}
}
class HelloCommandHandler {
@HandleCommand // OK
public execute(command: HelloCommand): Promise<string> {
return Promise.resolve(`Hello ${command.name}`);
}
@HandleCommand // Error (wrong parameter type)
public execute2(command: string): Promise<string> {
return Promise.resolve(`Hello ${command}`);
}
@HandleCommand // Error (wrong return type)
public execute3(command: HelloCommand): string {
return `Hello ${command.name}`;
}
}
【问题讨论】:
标签: typescript typescript-typings typescript-generics