【问题标题】:Typescript, restrict keys to array elements打字稿,将键限制为数组元素
【发布时间】:2019-11-19 21:51:30
【问题描述】:

已编辑:更改 ID 类型

我有一个包含以下值的数组

const ids: number[] = [45, 56];

const obj: any = {
  45: "HELLO",
  56: "WORLD",
};

我想输入我的对象的当前any 类型,以将其限制为我的ids 数组值。

我尝试了查找类型,但没有成功……

有什么想法吗?

问候

【问题讨论】:

  • 顺便说一句,const ids: string[] = [45, 56]; 行是错误的; 4556 不是 strings。

标签: typescript types typescript-typings


【解决方案1】:

您可以使用Record 映射类型。您还需要使用const 断言来捕获数组元素的文字类型:

const ids = [45, 56] as const;

const obj: Record<typeof ids[number], string> = {
    45: "HELLO",
    56: "WORLD",
};
const obj2: Record<typeof ids[number], string> = {
    45: "HELLO",
    56: "WORLD",
    57: "WORLD",  // error
};

【讨论】:

  • 哇!太棒了,我不知道 const 存在但它起作用了,据说这个数组是不可变的?
  • @ScreamZ 是的,它使数组只读,并且作为此元组和文字类型的副作用被保留(您将ids 类型作为[45, 56] 而不是number[]
【解决方案2】:

如果您需要创建一个函数,该函数返回一个可类型检查的对象,其键对应于数组:

function indexKeys<K extends string>(keys: readonly K[]) {
  type Result = Record<K, number>;

  const result: Result = {} as Result;

  const {length} = keys;

  for (let i = 0; i < length; i++) {
    const k = keys[i];

    result[k] = i;
  }

  return result;
};

这里类型检查器会抱怨:

// Property 'zz' does not exist on type 'Result'.
const {aa, zz} = indexKeys(['aa', 'bb']); 

【讨论】:

    猜你喜欢
    • 2021-01-10
    • 2023-03-19
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 2020-06-04
    相关资源
    最近更新 更多