When given an object, is it possible to create a second typed object that contains only a subset of the original keys with different value types? I attempted to use Partial<keyof ...>
, but it did not have the desired effect. Is there another approach to typing the second object (mapping
as shown in the example below)?
For example: (on TypeScript Playground)
const obj = {
a: '1',
b: '2',
c: 3,
d: 4,
e: false,
f: 'Hmmm',
};
// The following code snippet results in an 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
};
// The same error occurs when 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
};
// A similar error occurs when using Partial<> slightly 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
};