首页 > 解决方案 > 如何在 TypeScript 中使用动态键推断对象的类型?

问题描述

下面的代码在调用时给了我以下错误useObject

type{ [x: string]: string; }的参数不能分配给 type 的参数{ [K in keyof T]: string; }。ts(2345)

class Magic<T> {
  useKey(key: keyof T): void {
    this.useObject({ [key]: 'Hello' });
  }

  private useObject(object: { [K in keyof T]: string }): void {
    // Please note that this is a simplified example. In my real scenario
    // this interface is provided by an external package so it cannot change.
    console.log(object);
  }
}

在操场上打开

我希望 value{ [key]: 'Hello' }被推断为 type { [K in keyof T]: string },但它被推断为{ [K: string]: string }.

我试过添加as const无济于事。手动转换为预期类型有效,但需要我定义(有时是复杂的)类型,这应该是不必要的,因为类型在上下文中可用。

我该怎么做才能让 TypeScript 正确推断这种类型?

标签: typescript

解决方案


推荐阅读