简体   繁体   中英

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.

You could use thekeyof 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM