Skip to content

Spread and Generic #24060

Closed
Closed
@MrDesjardins

Description

@MrDesjardins

Search Terms

spread, generic, intersection

Suggestion

Spread operator does not work with 2.9.0-dev20180503 for generic but there is workaround by using Object.assign. Both should work. Currently, the spread syntax returns "Spread types may only be created from object types."

Related to this issue #13557

Use Cases

You want to merge two objects, one (or more) is generic.

Examples

    interface WithId {
        id: number;
    }
    interface User {
        name: string;
    }
    interface Developer extends User {
        favoriteLanguage: string;
    }
    function identifyUser<T extends User>(user: T): T & WithId {
        const newUser = Object.assign({}, user, { id: 1 });
        return newUser;
    }
    function identifyUser2<T extends User>(user: T): T & WithId {
        const newUser = {
            ...user, // This is not compiling
            id: 1
        };
        return newUser;
    }

Checklist

My suggestion meets these guidelines:
[x] This wouldn't be a breaking change in existing TypeScript / JavaScript code
[x] This wouldn't change the runtime behavior of existing JavaScript code
[x] This could be implemented without emitting different JS based on the types of the expressions
[x] This isn't a runtime feature (e.g. new expression-level syntax)

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions