Search code examples
typescripttyping

Can I add a prefix or suffix to the keys of a TypeScript interface/type which is programmatically generated?


I am wondering, if it is possible to to add a prefix or suffix to a TypeScript type which uses an array of strings as its keys.

type First = {
  one: string
  two: string
}

type Second = keyof First 

type Third = {
  [S in Second]: any
}

With this approach Third accepts the attributes one & two with any type. Which is amazing, as I only need to change the first type in order to have the others also updated.

Now I want a fourth type which is exactly the same as Third but I want to add a prefix to the keys. Like a dollar sign or something.

Desired result:

type Fourth = {
  $one: any
  $two: any
}

I could just hard code it but than I would have to adjust the Fourth type if the First type has been changed.

Thank you.


Solution

  • TS 4.1 has support for easy key remapping using template literal types:

    type First = {
      one: string
      two: string
    }
    
    type Fourth = {
        [K in keyof First as `$${K}`]: any
    }
    

    If you wanted to use the original type associated with each key instead of any (if you're using TS, you should want to avoid any when possible, after all!), replace

    : any
    

    with

    : First[K]