Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript type that is subset of keyof other type?

Tags:

typescript

Given an object, I would like to create a second typed object that has a subset of the first's keys and different value types. I tried Partial<keyof ...> but that seems to have no effect. Is there some other way I can type the second object (mapping in the example below).

Example: (on TypeScript Playground)

const obj = {
    a: '1',
    b: '2',
    c: 3,
    d: 4,
    e: false,
    f: 'Hmmm',
};

// Below gives error:
// Type '{ a: number; b: number; }' is missing the following properties from type 'Record<"a" | "b" | "c" | "d" | "e" | "f", number>': c, d, e, f(2739)
const mapping: Record<keyof typeof obj, number> = {
    a: 10,
    b: 20
};


// basically same error using Partial<>
// Type '{ a: number; b: number; }' is missing the following properties from type 'Record<Partial<"a" | "b" | "c" | "d" | "e" | "f">, number>': c, d, e, f(2739)
const mapping2: Record<Partial<keyof typeof obj>, number> = {
    a: 10,
    b: 20
};

// basically same error using Partial<> a little differently
// Type '{ a: number; b: number; }' is missing the following properties from type 'Record<Partial<"a" | "b" | "c" | "d" | "e" | "f">, number>': c, d, e, f(2739)
const mapping3: Record<keyof Partial<typeof obj>, number> = {
    a: 10,
    b: 20
};
like image 310
Samuel Neff Avatar asked Oct 12 '25 10:10

Samuel Neff


1 Answers

You can create the type without using Partial, since Partial doesn't really change the value type as you needed here:

const mapping: { [K in keyof typeof obj]?: number }= {
    a: 10,
    b: 20
};

Playground

like image 78
Psidom Avatar answered Oct 16 '25 11:10

Psidom