首页 > 解决方案 > 是否可以从 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.

标签: typescript

解决方案


这是实现目标的一种方式:

打字稿游乐场链接

const arr = ["foo", "bar"] as const;

type lol = {
  [k in typeof arr[number]]: string;
};

/** returns
type lol = {
    foo: string;
    bar: string;
}
*/

推荐阅读