Skip to content

Spread operator fails for object type generics #26412

Closed
@opiation

Description

@opiation

TypeScript 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 the object 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:
#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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions