typescript - 如何在 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 正确推断这种类型?
解决方案
推荐阅读
- php - 在 Laravel 8 中导出到 excel 时添加列名
- azure - GetAuthenticationCookie 返回“值不能为空。参数名称:cookieHeader”的 SharePoint Online 问题
- laravel - 在laravel中未定义路线[员工]?
- java - JPA getResultList - 如何从响应中获取价值?
- javascript - 将多个 DataTable 的行从一个刀片传递到 admin.blade
- sql - 是否所有关系数据库都具有相同的语法
- svn - 如何在命令提示符下使用 svn:externals
- php - CakePHP 和 MySQL 获取记录:一次少量或连续数百条
- pandas - 在数据系列上应用 lower() 方法时,pandas 应用地图函数抛出错误
- python - 我需要对 catboost 的源代码进行哪些更改才能将 max_depth 增加到 16 以上?