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
};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With