首页 > 解决方案 > 如何用所有相同类型的 n 个键简明地定义打字稿类型

问题描述

对于一些科学计算,我有一个输入参数对象,都是数字类型。手动输入所有内容如下所示:

type parameters = {gdp: number, interest: number, inflation: number, ...}

有没有办法使用所有分配了相同数字类型的键数组来做同样的事情?原则上可能是这样的:

type parameteres = {(...[gdp, interest, inflation]): number}

谢谢!

标签: typescripttypescript-typings

解决方案


与Wiktor 的评论相呼应,这里有一些不同的方法可以定义类型,并保持DRY

TS Playground 链接

type A = { [K in 'gdp' | 'interest' | 'inflation']: number };
type B = Record<'gdp' | 'interest' | 'inflation', number>;

// if you want access to the keys as a union elsewhere
type InputKeyCD = 'gdp' | 'interest' | 'inflation';
type C = { [K in InputKeyCD]: number };
type D = Record<InputKeyCD, number>;

// if you need the keys as runtime data, too
const inputKeys = ['gdp', 'interest', 'inflation'] as const;
type InputKeyEF = typeof inputKeys[number];
type E = { [K in InputKeyEF]: number };
type F = Record<InputKeyEF, number>;

type InputParams = A | B | C | D | E | F;
declare const input: InputParams;
input.gdp // number
input.interest// number
input.inflation// number
input.average // error

推荐阅读