Issue
function foo<T extends object>(t: T): T {
return {
...t // Error: [ts] Spread types may only be created from object types.
}
}
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?
Solution
This is fixed in TypeScript Version 3.2. See Release Notes.
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;
}
or you can use Object.assign
which has proper type definitions.
function foo<T extends object>(t: T): T {
return Object.assign({}, t);
}
Answered By - jmattheis
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.