Issue
I have an object which I need to derive types from, see obj:
const obj = {
PROP1: {
type: 'number',
},
PROP2: {
type: 'string',
},
PROP3: {
type: 'boolean',
},
PROP4: {
type: 'string',
},
}
Which I now would wish to transform to type like:
type ObjType = {
PROP1: number;
PROP2: string;
PROP3: boolean;
PROP4: string;
};
All my solutions have failed and its something I really would like to achieve so help is always appreciated.
Solution
In order for this to possibly work you need to change obj
so that the compiler keeps track of the literal types of the type
subproperties. Otherwise the compiler will just assume that they are all string
; that's a reasonable assumption in general, since people often want to change the values of string properties, but it throws away the information you care about.
The easiest way to ask the compiler to track the literal types of things in an object literal is to use a const assertion:
const obj = {
PROP1: {
type: 'number',
},
PROP2: {
type: 'string',
},
PROP3: {
type: 'boolean',
},
PROP4: {
type: 'string',
},
} as const;
Now we can proceed.
You'll need to make your own mapping from names of types to actual types; there's no built-in functionality like this in TypeScript:
interface TypeMap {
number: number;
string: string;
boolean: boolean;
// add other names you care about
}
Once you do that you can write a mapped type to iterate over the properties in typeof obj
and convert them as desired:
type ObjType = { -readonly [K in keyof typeof obj]: TypeMap[typeof obj[K]["type"]] }
/* type ObjType = {
PROP1: number;
PROP2: string;
PROP3: boolean;
PROP4: string;
} */
Answered By - jcalz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.