typescript - 在 Typescript 中约束对象的值类型
问题描述
在打字稿中,如何为可以具有任何键的普通旧 javascript 对象编写类型签名,但值始终是字符串。例如,{a:"foo"}
,{b:"bar"}
都是有效值,但{a:[1,2,3]}
不是{b:3}
。
我希望能够写出类似的东西
let foo : {*: string} = {a: "foo"}
目前,我正在使用any
它来实现这一点,但这并不像我想要的那样精确。
解决方案
您可以使用索引签名来声明所有值都是字符串...
type Example = { [key: string]: string };
例子:
type Example = { [key: string]: string };
const a: Example = {
"anything": "any string", // ok
anotherkey: "a string", // ok
thirdKey: 1 // Error
};
推荐阅读
- mongodb - 在数组中查找字符串
- javascript - 从 youtube 嵌入 url 获取 YouTube ID
- python - 如何在 Tensorflow 中使用“transform_graph”
- java - 是否保证会抛出 Java OutOfMemoryError
- c# - 如何使用 C# 在 64 位机中获取所有 ODBC 或 Access 数据源的列表
- c# - Razor 页面中确认模式后的信息模式
- html - Font Awesome 图标未显示 Impreza thme
- mysql - MySQL 还不支持 Limit&& in/all?
- python - 我如何显示在 django 中花费的平均时间(in_time 和 out_time)?我使用聚合吗?
- php - 在 csv 文件中写入结果时遇到问题