typescript - 是否可以从 typescript 中的 ["foo","far"] 之类的数组创建接口
问题描述
我努力了
const arr=["foo", "bar"]
type lol={
[key in arr]:string
}
我已经尝试了很多事情,但不会得到预期的答案,我认为这是不可能的。预期输出一个带有 arr 具有的键的接口,这可能与值有关 我怎样才能做出类似的事情?这就是打字稿所说的
A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.
解决方案
这是实现目标的一种方式:
const arr = ["foo", "bar"] as const;
type lol = {
[k in typeof arr[number]]: string;
};
/** returns
type lol = {
foo: string;
bar: string;
}
*/
推荐阅读
- sql - 在这个 SQL 模式中可以改进什么?
- oracle-data-integrator - 通过 ODI 12c 的平面文件行号
- javascript - 你如何在动态项目上做 hasClass
- ffmpeg - ffmpeg在录制时播放RTSP流
- c# - 通过 GET 方法发送字符串列表参数
- android - 使用改造的多部分请求无法连接到端点
- javascript - 在 Node 中使用 fs.readFile 串行读取文件?
- android - 在 WebView 中隐藏没有 Id 和类名的 HTML 元素
- python - 为什么随机生成器不起作用?Python
- ruby-on-rails - 如何使 activerecord-import 使用序列