Spread operator fails for object type generics
See original GitHub issueTypeScript Version: 3.0
Search Terms: generic, spread, object types, spread types, spread operator
Code
function shallowCopy<T extends object>(state: T): T {
return {
...state
}
}
Expected behavior:
Should compile as only state
’s properties are being shallow-copied to the returned result and thus meets the T
type.
Actual behavior: Does not compile with the following error message:
> Spread types may only be created from object types.
If T extends object
, is it not then an object type
? If not, what type
or interface
can be defined that is an object type
and is not exactly {}
or object
?
Possible ways forward:
- If the compiler does not properly recognize
T extends object
as an object type, perhaps this should be implemented to better support spread/rest operators in modern ecmascript syntax. - If
T extends object
is a recognized object type, the compiler error should be amended to something like “Spread types may only be created from theobject
type in generics” - Silently lock and close this issue adding documentation that states “The spread operator does not support generics extending
object
”
Playground Link: Contrived example
Related Issues:
https://github.com/Microsoft/TypeScript/pull/13288 - While this seems like the use case was addressed by @RyanCavanaugh , the resulting workaround suggests far more explicit typing than should be required by the compiler to infer the types in the example provided. While closing that PR might have been the protocol, it seemed more effectively to silence the community request for spread operator support with generics extending from object
.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:25
- Comments:9 (3 by maintainers)
Top GitHub Comments
:extremely long sigh:
Came here because of: