• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

375
Vistas
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.

about 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda