Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
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 Respuestas
Responde la pregunta

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 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda