Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I do this type transformation in TypeScript?

type U = {
  foo: {
    id: '001'
    name: 'alan'
  }
  bar: {
    id: '002'
    name: 'dan'
  }
}

type V = {
  '001': 'alan'
  '002': 'dan'
}

// type Trans<T> = ...
// V === Trans<U>

Sorry I don’t know how to name it, but anyone can tell me how to archive that?

I’ve already been trying for several hours but I can only get

// this is not I want
type V = {
  '001': 'alan' | 'dan'
  '002': 'alan' | 'dan'
}

Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The easiest way to do this would be with a mapped type and a remapped key (docs):

type V = {[K in keyof U as U[K]['id']]: U[K]['name']}
// V = { "001": "alan"; "002": "dan" }

TypeScript playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading