Type { [x: string]: T[S]; } is not assignable to type 'Partial<T>'

Viewed 336

I have this code part, that is pretty simple:

interface A {
    z: string;
    y: number;
}

let newA = <T, S extends keyof T>(key: S, value: T[S]): Partial<T> => {
    return {[key]: value};
}

And I see an error message: Type '{ [x: string]: T[S]; }' is not assignable to type 'Partial<T>'

I can suppose that the problem is related to {}, that it always maps key to be string

But even with explicit type says that that should be string I have no result

Only one working solution was to just remove Partial<T>, but that's not a good one

Hope to get some answer from some expert-level typescript guy who can describe the mechanism of that problem and also to get the solution of this situation

Note! The problem is related only to generic case. Without that everything goes okay.

Typescript Playground with this code

1 Answers

You don't need to use Partial. Objects with computed keys are always infered to {[prop:string]:any infered type}

You can overload your function to avoid such behavior:

type Json =
    | null
    | string
    | number
    | boolean
    | Array<JSON>
    | {
        [prop: string]: Json
    }

function record<Key extends PropertyKey, Value extends Json>(key: Key, value: Value): Record<Key, Value>
function record<Key extends PropertyKey, Value extends Json>(key: Key, value: Value) {
    return { [key]: value };
}

const result = record('a', 42) // Record<"a", 42>
Related