typescript - 如何用所有相同类型的 n 个键简明地定义打字稿类型
问题描述
对于一些科学计算,我有一个输入参数对象,都是数字类型。手动输入所有内容如下所示:
type parameters = {gdp: number, interest: number, inflation: number, ...}
有没有办法使用所有分配了相同数字类型的键数组来做同样的事情?原则上可能是这样的:
type parameteres = {(...[gdp, interest, inflation]): number}
谢谢!
解决方案
与Wiktor 的评论相呼应,这里有一些不同的方法可以定义类型,并保持DRY:
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
推荐阅读
- javascript - 在引导程序上对齐按钮内的两个元素时出现问题
- google-drive-api - 有关文件是否已保存的信息
- jdbc - Kafka-Connect JDBC Sink 连接器和 Avro 在第二次插入时失败
- excel - 仅在 ComboBox 中显示可见工作表
- python-3.x - 如何使用 apply 轻松更改 tf-idf 相似性数据框
- android - Android Studio XML Parse 错误:prolog 中不允许内容
- java - org.hibernate.hql.internal.ast.QuerySyntaxException:即使我使用实体的类名,也没有映射员工
- android - 无法覆盖片段中的 onConfigurationChange
- leaflet - LeafletJS中的笛卡尔坐标到LatLng
- flutter - 我想在单击 onTap 时更改作为 ListView 子项的 CustomListTile 的颜色,并将其他子项颜色设置为默认颜色?