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

Typescript: Generate types from an object

I just started learning Typescript and need some help with this example.


const alphabet = {
    'a': {lower: 97, upper: 65},
    'b': {lower: 98, upper: 66}
}

type Char = 'a' | 'b'

function printSome(char: Char){
    console.log(alphabet[char])
}

Instead of manually updating the Char type, I’d like to dynamically update generate types from the alphabet object.

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 :

You could use the keyof and typeof operators:

const alphabet = {
    'a': {lower: 97, upper: 65},
    'b': {lower: 98, upper: 66}
}

type Char = keyof typeof alphabet;

function printSome(char: Char){
    console.log(alphabet[char])
}

This basically turns alphabet into a type and then gets the keys of that type.

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