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

192
Visualizações
Why does this TypeScript program compile?

Let's start with an apology for the overly generic question, but I am wrecking my head how to narrow it down due to lack of understanding of what's happening here, so will adjust based on comments / answers.

I have created a sample program on TypeScript Playground that should not compile but does (using latest version of TypeScript, v4.5.2 as of this writing.) I am trying to understand why this compiles in order to understand what other bad programs might sneak past the type checker and go undetected. Here is another version of the program that shows the problem at runtime. Are there any options I have overlooked or anything I can do to have this program not type check?

For convenience, I inline the program in question here as well:

type Settings = { 'a': boolean; 'b': string }

function setSetting<K extends keyof Settings>(p: K, v: Settings[K]): void {}

// setSetting('a', 100) // good; it fails
setSetting('a', true); // good; compiles

function breakSetSetting(k: keyof Settings, v: boolean): void {
  setSetting(k, v);
}

breakSetSetting('b', true); // bad; it compiles!

Update: As per comment by @crashmstr using generics for breakSettings makes the program not compile, however, it's still unclear to me why it was allowed to compile before.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

When you define K, you are defining it to be 'a' | 'b' (which is keyof K). This means that v would be Settings['a' | 'b'] which evaluates to boolean | string. Now when your breakSetSetting passes a boolean to setSetting, boolean is in the scope of boolean | string, making the compiler pass.

over 4 years ago · Santiago Trujillo 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