Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
Typescript: Generate types from an object with the interface

It's the second part for my question that was asked here. I've been helped with the solution for my previous problem, but once I added the interface for the alphabet object, Typescript stopped detecting that I provided the incorrect value.


interface ICharMap {
    lower: number
    upper: number
}

const alphabet: {[key: string]: ICharMap} = {
    'a': {lower: 97, upper: 65},
    'b': {lower: 98, upper: 66}
}

type Char = keyof typeof alphabet;

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

printSome('c') \\ Typescript does not detect that the incorrect value is passed.
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could do something like this:

interface ICharMap {
  lower: number
  upper: number
}

type Letter = 'a' | 'b'

const alphabet: Record<Letter, ICharMap> = {
  'a': {lower: 97, upper: 65},
  'b': {lower: 98, upper: 66}
}

function printSome(char: Letter){
  console.log(char);
  console.log(alphabet[char]); // no error; TS knows that char is in alphabet
}

printSome('c') // error
about 4 years ago · Juan Pablo Isaza Relatório

0

It is because your alphabet has {[key: string]} so when you do keyof typeof alphabet it returns string, with that you are allowed to pass any string.

If you modify your script like this then it will tell typescript that you should pass only 'a' and 'b'

interface ICharMap {
    lower: number
    upper: number
}

type keys = 'a' | 'b';

const alphabet: {[key in keys]: ICharMap} = {
    'a': {lower: 97, upper: 65},
    'b': {lower: 98, upper: 66}
}

type Char = keyof typeof alphabet;

function printSome(char: Char){
    console.log(char)
}
printSome('c')
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda