如何使typecript只允许从数组中取值?

问题描述 投票:1回答:1

这是我的辅助函数

type ReturnType = { [k1: string]: { [k2: string]: string } } ;
function createObject(arr: string[]) : ReturnType {
  const tempObj : ReturnType = {};
  arr.forEach((item) => {
    tempObj[item] = {
      x: `${item}-x`,
      y: `${item}-y`,
      z: `${item}-z`,
    };
  });

  return tempObj;
}

现在,我使用助记函数创建了一个新的对象,如何修改我的助记函数,使typescript在值不是来自给定数组时产生错误。

const myObj = createObject(['a', 'b', 'c']);

我如何修改我的助记函数,使typescript在值不是来自给定数组时产生错误。

myObj.a.x; // Correct
myObj.something.other; // must give error
typescript generics
1个回答
1
投票
type Foo<T extends readonly string[]> = { [Key in T[number]]: { x: string, y: string, z: string } }
function createObject<T extends readonly string[]>(array: T): Foo<T> {
  const tempObj = {} as any
  array.forEach((item) => {
    tempObj[item] = {
      x: `${item}-x`,
      y: `${item}-y`,
      z: `${item}-z`,
    };
  });

  return tempObj;
}
const apple = createObject(['a', 'b', 'c'] as const)
© www.soinside.com 2019 - 2024. All rights reserved.