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
Arrays 键入特定值的数组,其中每个值最多只能出现一次?(打字稿)_Arrays_Typescript_Subset - Fatal编程技术网

Arrays 键入特定值的数组,其中每个值最多只能出现一次?(打字稿)

Arrays 键入特定值的数组,其中每个值最多只能出现一次?(打字稿),arrays,typescript,subset,Arrays,Typescript,Subset,假设我有如下函数: function getUserInfo(desiredProperties: ('name' | 'age' | 'salary')[]) { const userInfo: Record<string, unknown> = {}; for (const propertyName of desiredProperties) { userInfo[propertyName] = fetchEffortfullyFromDatabase(...);

假设我有如下函数:

function getUserInfo(desiredProperties: ('name' | 'age' | 'salary')[]) {
  const userInfo: Record<string, unknown> = {};
  for (const propertyName of desiredProperties) {
    userInfo[propertyName] = fetchEffortfullyFromDatabase(...);
  }
  return userInfo;
}
一切都很好。 但是没有什么能阻止你打这样的电话

const userInfo = getUserInfo(['name', 'name', 'name', ...]);
触发许多不必要的数据库访问。当然,这可以在运行时在
getUserInfo
中简单地处理,但我希望编译器能够识别并禁止此类调用

我可以将
('name'|'age'|'salary')[]
更改为所有可能的属性名称组合的并集,即
['name']|['name'、'age']|['name'、'age'、'salary']|['age']|……
,但这对于三个值来说太单调乏味了,而且很难实现更多(尤其是在考虑订单的情况下)


那么,有没有其他方法可以获得所需的输入?可能类似于
所有组合

您可以使用
设置
类型功能仅提取传递参数的唯一成员:

function getUserInfo(desiredProperties: ('name' | 'age' | 'salary')[]) {
  const uniqueMembers = new Set(desiredProperties); // this extract only unique members of array
  const userInfo: Record<string, unknown> = {};
  for (const propertyName of uniqueMembers) { // and here you iterate only through unique members
    userInfo[propertyName] = fetchEffortfullyFromDatabase(...);
  }
  return userInfo;
}

let userInfo = getUserInfo(['name', 'salary']);

userInfo = getUserInfo(['name', 'name', 'name']);
function getUserInfo(desiredProperties: ('name' | 'age' | 'salary')[]) {
  const uniqueMembers = new Set(desiredProperties); // this extract only unique members of array
  const userInfo: Record<string, unknown> = {};
  for (const propertyName of uniqueMembers) { // and here you iterate only through unique members
    userInfo[propertyName] = fetchEffortfullyFromDatabase(...);
  }
  return userInfo;
}

let userInfo = getUserInfo(['name', 'salary']);

userInfo = getUserInfo(['name', 'name', 'name']);
const userInfo = getUserInfo(new Set(['name', 'salary']));