Reputation: 422
I have the following object:
const foo = {
fieldAnt: "foo",
fieldCab: "baz"
};
I'd like to automatically map that to a type with the keys made to uppercase and underscored:
type FIELDS = {
FIELD_ANT: "fieldAnt",
FIELD_CAB: "fieldCab"
}
Is it possible using keyof
or type mapping to programmatically achieve this with typescript?
Upvotes: 7
Views: 3514
Reputation: 2416
A little late :P but, with a little help I was able to do it:
const foo = {
fieldAnt: "foo",
fieldCab: "baz"
};
type CamelToSnakeCase<S extends string> =
S extends `${infer T}${infer U}` ?
`${T extends Capitalize<T> ? "_" : ""}${Lowercase<T>}${CamelToSnakeCase<U>}` :
S
type Convert<T> = { [P in keyof T as Uppercase<CamelToSnakeCase<string & P>>]: P }
type Fields = Convert<typeof foo>
// type Fields = {
// FIELD_ANT: "fieldAnt",
// FIELD_CAB: "fieldCab"
// }
Upvotes: 11