Omair Vaiyani
Omair Vaiyani

Reputation: 422

Typescript mapping keys to uppercase

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

Answers (1)

Buszmen
Buszmen

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" 
// }

TS Playground

Upvotes: 11

Related Questions