7

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?

4
  • I don't think so... may I ask you why this would be useful? Commented Mar 19, 2020 at 18:45
  • Typescript only provides types, you're kinda asking that It actually affects and changes objects. Commented Mar 19, 2020 at 18:47
  • unfortunately you cannot do string manipulation using typescript types so while you could enforce the FIELDS values being equal to the keyof foo. You could not created the required uppercase, underscored keys themselves. Commented Mar 19, 2020 at 18:57
  • The idea is that I would run a function to actually create that object at runtime, but need the types present for static checks Commented Mar 20, 2020 at 9:01

1 Answer 1

12

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.