Typescript 接口问题:当我们有一个类似 const 的列表时,如何获取类似 t 的类型

Typescript interface problem: how to get the type like t when we have a const like list

const list = [
  {
    label: "phone",
    defaultValue: "1203981209",
  },
  {
    label: "isMan",
    defaultValue: false,
  },
  {
    label: "age",
    defaultValue: 22,
  },
];

type t = {
  phone: string;
  isMan: boolean;
  age: number;
};

我们有 list.And 如何在 Typescript 中获取 t。 我试着写类似 type t = {[k in typeof list[number]["label"]]: typeof list[number]["defaultValue"];}; 的东西,但那不起作用。

原始对象需要正确键入才能使其工作 - 因为您需要新对象中键的文字 label 值,所以它们需要是 as const,所以它们不会t 扩大到 string。 (我没有看到在整个对象上使用 as const 的好方法,因为这样 values 不会变宽 - 如果你走那条路,你会必须有一个助手类型来转换,例如,"1203981209"string 等等)。

const l = [
  {
    label: "phone" as const,
    defaultValue: "1203981209",
  },
  {
    label: "isMan" as const,
    defaultValue: false,
  },
  {
    label: "age" as const,
    defaultValue: 22,
  },
];
type T = {
    [Prop in typeof l[number] as Prop["label"]]: Prop["defaultValue"];
};

如果您的用例允许,我会建议采用其他方式,例如

interface PropertyDefaultValue<K extends keyof t = keyof t> {
  label: K;
  defaultValue: t[K];
}

const list: PropertyDefaultValue[] = ....

就是说,在我写这篇文章时,@CertainPerformace 发布了他们的答案,我认为在许多用例中我比他们更喜欢他们的答案。

也就是说,我的不需要定义所有默认属性。

另外,你确定这是你要走的路吗?我总是用我的默认值定义一个对象,然后使用 myFilledObj = Object.assign({}, myDefaultObj, mySpecificObjBeforeFillingDefaultValues)

充实我的对象