Skip to content

Creating object literal with generic key type fails to compile #22060

Closed
@Rogach

Description

@Rogach

TypeScript Version: 2.8.0-dev.2018022 or 2.7.2

Search Terms: generic keyof object literal

Code

function foo<S>(state: S, key: keyof S) {
    let newState: { [P in keyof S]: S[P] } = {[key]: state[key]};
}

Expected behavior:
Expected to compile, since I just created a simple literal object.

Actual behavior:

test.ts(2,9): error TS2322: Type '{ [x: string]: S[keyof S]; }' is not assignable to type '{ [P in keyof S]: S[P]; }'.

Seems that type is removed from key and replaced with string. I'm aware that all object keys are strings, but how do I then create an instance of Pick<S, P>?

Possibly Related Issues: #22053

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