Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使typescript只允许数组中的值?_Typescript_Generics - Fatal编程技术网

如何使typescript只允许数组中的值?

如何使typescript只允许数组中的值?,typescript,generics,Typescript,Generics,这是我的助手函数 type ReturnType={[k1:string]:{[k2:string]:string}; 函数createObject(arr:string[]):ReturnType{ const tempObj:ReturnType={}; arr.forEach((项目)=>{ tempObj[项目]={ x:`${item}-x`, y:`${item}-y`, z:`${item}-z`, }; }); 返回tempObj; } 现在,我使用helper函数创建一个新对

这是我的助手函数

type ReturnType={[k1:string]:{[k2:string]:string};
函数createObject(arr:string[]):ReturnType{
const tempObj:ReturnType={};
arr.forEach((项目)=>{
tempObj[项目]={
x:`${item}-x`,
y:`${item}-y`,
z:`${item}-z`,
};
});
返回tempObj;
}
现在,我使用helper函数创建一个新对象

constmyobj=createObject(['a','b','c']);
如何修改helper函数,使typescript在值不是来自给定数组时生成错误

myObj.a.x;//对的
myObj.something.other;//必须给出错误
键入Foo={[Key in T[number]]:{x:string,y:string,z:string}
函数createObject(数组:T):Foo{
常量tempObj={}如有
array.forEach((项)=>{
tempObj[项目]={
x:`${item}-x`,
y:`${item}-y`,
z:`${item}-z`,
};
});
返回tempObj;
}
常量apple=createObject(['a','b','c']作为常量)
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)