Home > Net >  Typescript: Generate types from an object
Typescript: Generate types from an object

Time:02-16

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.

CodePudding user response:

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.

  • Related