Skip to content

Object type not assignable to equivalent value of mapped type #25010

Closed
@ethanroday

Description

@ethanroday

Code

// Pack<{ a: number }> is { a: { value: number } }
type Pack<T> = { [K in keyof T]: { value: T[K] } };

function patch<T, K extends keyof T>(obj: Partial<Pack<T>>, key: K, value: T[K]) {
    obj[key] = { value }; // error: Type '{ value: T[K]; }' is not assignable to type 'Pack<T>[K]'.
}

Example usage of patch():

type SomeType = {
  a: number, b: string
};

const obj: Partial<Pack<SomeType>> = {
    a: { value: 1 }
}

patch(obj, 'b', 'foo'); // desired outcome is for obj.b to equal 'foo'

Expected behavior:

Definition of patch() function should be fine, and calling should produce the desired outcome.

Actual behavior:

patch() function fails to compile with error Type '{ value: T[K]; }' is not assignable to type 'Pack<T>[K]' even though { value: T[K] } does appear to be assignable to Pack<T>[K]:

function getPack<T, K extends keyof T>(obj: T, key: K): Pack<T>[K]  {
    const value = obj[key]; // T[K]
    return { value }; // { value: T[K]; }
}

Playground Link:
Additional examples here: https://bit.ly/2le5qZq

Metadata

Metadata

Assignees

Labels

FixedA PR has been merged for this issueNeeds InvestigationThis issue needs a team member to investigate its status.

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions