typescript - 将接口(interface)转换为字典

标签 typescript casting

我有一个函数 logNumbers,它接受一个字典,其中所有键都是字符串,所有值都是数字。我想用属于更严格接口(interface)但仍满足这些条件的对象调用 logNumbers

interface NumberDictionary {
  [key: string]: number;
}

interface StatisticsResult {
  mean: number;
  mode: number;
  median: number;
}

function logNumbers(numDict: NumberDictionary) { ... }

const results: StatisticsResult = {
  mean: 1,
  mode: 2,
  median: 2,
};

// 
// Error:
//   Argument of type 'StatisticsResult' is not assignable to parameter of type 'NumberDictionary'.
//   Index signature is missing in type 'StatisticsResult'.
//
logNumbers(results);

我希望 StatisticsResult 保持不变,并以某种方式修改 logNumbers 的签名。有没有办法做到这一点?也许我可以向 typescript 发出信号,表示不会向 logNumbers 中的 numDict 添加新键?

Reproduction in TypeScript Playground

最佳答案

如果您的目标是将函数限制为仅具有数字属性的对象,则可以使用将泛型类型参数限制为仅具有数字的记录。

  interface StatisticsResult {
    mean: number;
    mode: number;
    median: number;
  }

  function logNumbers<T extends Record<keyof T, number>>(num: T) {
    // Log the numbers as a table or something
  }

  const results: StatisticsResult = {
    mean: 1,
    mode: 2,
    median: 2,
  };

  //ok
  logNumbers(results);

关于typescript - 将接口(interface)转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54239647/

相关文章:

java - 使用 Mockito 监视对象

javascript - 如何使用 Visual Studio 将 typescript 网站发布到 GitHub Pages?

javascript - 对 "big"文件使用 PhoneGap FileWriter.write

ios - Swift 中的类型转换

python - 尝试将字符串转换为整数的 Pandas 错误

casting - 将 Vec<u32> 就地转换为 Vec<u8> 且开销最小

java - 如何在 OpenCL 中将 int 转换为 float?

node.js - 在 typescript 中使用带有 Angular 6 的 Node 短 ID 模块

node.js - 如何将 'process.on' 更改为基于 RxJS 风格的事件?

reactjs - 类型 '({ items }: PropsWithChildren<TodoProps>) => Element[]' 不可分配给类型 'FunctionComponent<TodoProps>'