打字稿:传播类型只能从对象类型创建 [英] Typescript: Spread types may only be created from object types
问题描述
function foo<T extends object>(t: T): T {
return {
...t // Error: [ts] Spread types may only be created from object types.
}
}
我知道 github 上存在问题,但我无法弄清楚哪些已修复,哪些未修复,并且他们有 2695 个未解决的问题.所以我在这里发帖.我使用的是最新的 Typescript 2.9.2.
I am aware that there are issues on github, but I can't figure out what is fixed and what is not and they have 2695 open issues. So I am posting here. I am using latest Typescript 2.9.2.
上面的代码应该不行吧?如果可能,我该如何解决?
Should the above code not work? And how can I fix it if possible?
推荐答案
此问题已在 TypeScript 3.2 版中修复.请参阅发行说明一>.
This is fixed in TypeScript Version 3.2. See Release Notes.
看起来像泛型传播尚不支持,但有一个关于它的 GitHub 问题:微软/TypeScript#10727.
Looks like spread with a generic type isn't supported yet, but there is a GitHub issue about it: Microsoft/TypeScript#10727.
For now you can either use type assertion like @Jevgeni commented:
function foo<T extends object>(t: T): T {
return { ...(t as object) } as T;
}
或者您可以使用具有正确类型定义的 Object.assign
.
or you can use Object.assign
which has proper type definitions.
function foo<T extends object>(t: T): T {
return Object.assign({}, t);
}
这篇关于打字稿:传播类型只能从对象类型创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!