typescript - 打字稿不能将对象文字分配给泛型类型
问题描述
如果我尝试将对象文字与具有类型约束的泛型类型一起使用,则会出现类型错误,我正在努力找出原因:
type WithKey = {
readonly akey: string;
}
function listOfThings<T extends WithKey>(one: T) {
// This is ok
const result2: Array<T> = [one];
//This errors with Type '{ akey: string; }' is not assignable to type 'T'.
const result: Array<T> = [{ akey: 'foo' }];
return result;
}
解决方案
它不接受的原因{ akey: 'foo' }
是因为T
只有extends WithKey
,所以字面上的对象WithKey
不一定可以分配给T
. 例如:
listOfThings<{ akey: string; aflag: boolean }>()
{ akey: 'foo' }
不满足{ akey: string; aflag: boolean }
。
您可以使用断言强制编译器:
const result: Array<T> = [{ akey: 'foo' } as T];
但这会为您打开一个错误,因为在第一个示例中会编译但在运行时不是真的。似乎这不是您想要的,或者类型没有描述您想要的。
推荐阅读
- ansible - 对于需要 sudo 的多个任务,如何让 ansible 只运行一次 sudo?
- c# - 如何使用 Graph API 在 C# 中获取 Teams 组织层次结构数据
- perl - Bugzilla - 主机升级 perl - 浏览/搜索是唯一无法以任何方式更新的功能?
- python - Pandas Json:“TypeError:to_json() 得到了一个意外的关键字参数‘缩进’”
- winapi - 尝试填充动态菜单时断言 IsMenu 异常
- xml - 如何获得正确的输出格式
- python - 谷歌电子表格api python - 将内容附加到空白行
- python - TensorFlow 的 while 循环比传统的 while 循环慢
- c - 三叉树搜索异常?
- javascript - 地理数据下拉配置器未显示国家/地区