如何根据参数的值缩小函数内的返回类型?

问题描述 投票:0回答:1

我试图将接口的方法组合成一个带有附加

operation
参数的函数。可以按预期调用生成的函数,但似乎我无法在函数内缩小返回类型。

我之前的一个问题的答案对于缩小参数类型很有帮助,但是函数内的返回类型的缩小对我来说仍然是一个谜: interface Machine { doSomething: (arg: number) => string; doSomethingElse: (args: boolean) => number; }; type MachineParameters = { [K in keyof Machine]: [K, ...Parameters<Machine[K]>]; }[keyof Machine]; const execute = <T extends MachineParameters>(...args: T): ReturnType<Machine[T[0]]> => { switch (args[0]) { case "doSomething": // Error: Type '`${number}`' is not assignable to type 'MachineReturnTypes[T[0]]'. return `${args[1]}`; case "doSomethingElse": // Error: Type 'number' is not assignable to type 'MachineReturnTypes[T[0]]'. return Number(args[1]); default: throw new Error("Unknown operation"); } }; // Works: string const x = execute("doSomething", 1); // Works: number const y = execute("doSomethingElse", true);

游乐场

typescript
1个回答
0
投票

interface Machine { ... } function execute(operation: 'doSomething', arg: number): string; function execute(operation: 'doSomethingElse', arg: boolean): number; function execute(operation: keyof Machine, args: any): any { ... }

看游乐场

© www.soinside.com 2019 - 2024. All rights reserved.