【发布时间】:2020-04-09 12:18:15
【问题描述】:
是否可以从键/值映射推断元组?
基本上它可能是从联合类型到元组的转换(比如https://github.com/microsoft/TypeScript/issues/13298#issuecomment-482330241)
但我希望有一个更优雅和编译器友好的解决方案,比如手册中建议的元组函数 (http://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#example-2)
interface ParamMapping {
a: boolean;
b: string;
c: 'foo' | 'bar';
}
declare function param<K extends keyof ParamMapping>(...name: K[]): ParamMapping[K];
// posible solutions:
// declare function param<K extends keyof ParamMapping>(...name: K[]): ParamMapping[...K];
// declare function param<K extends keyof ParamMapping>(...name: K[]): ...ParamMapping[K];
// declare function param<K extends (keyof ParamMapping)[]>(...name: K): for P of K : ParamMapping[K];
declare function param(...name: string[]): unknown[];
// typed as unknown[]
const p1 = param('baz', 'qux');
// *should be* typed as [boolean, string]
const p2 = param('a', 'b');
// *should be* typed as [string, 'foo' | 'bar']
const p3 = param('b', 'c');
// *should be* typed as [boolean, string, 'foo' | 'bar']
const p4 = param('a', 'b', 'c');
【问题讨论】:
标签: typescript types tuples