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

142
Vistas
How can object keys be typed to match a given pattern with unlimited combinations?

I need to make sure an object only has keys that follow a pattern. That pattern i: "{integer}a+{integer}c". It would look like:

{
    "2a+1c": {
        // ...
    }
}

How can I ensure that any new key added to this object follows this pattern, without laying out all possible keys (as it is not feasible)?

To maybe shed some light to what I'm thinking about, here is how you can make sure that an object only has keys that belong to an enum:

type ObjectWithEnumedKeys = {
  [key in TheEnum]?: number;
}

I'm not looking for a solution that uses logic (methods in a class, or a closure) to control this.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Is there a way to type an object in a way that its keys can only be strings that match a given Regex?

No.

about 4 years ago · Juan Pablo Isaza Denunciar

0

TypeScript 4.4 introduced the usage of Template Literal Types in index signatures. While they currently allow any number, not just integers, in the interpolations, it's not exactly what you asked for, but comes very close:

type TheEnum = `${number}a+${number}c`;
type ObjectWithEnumedKeys = {
  [key in TheEnum]?: number;
}


const x: ObjectWithEnumedKeys = {
  "2a+1c": 3, // works as expected
  "5.5a+3.1c": 8.6, // accepted as well, hm
  "error": undefined, // complains that "property 'error' does not exist in type 'ObjectWithEnumedKeys'", as expected
}

(Demo in Playground)

Regex-validated string types that would let you properly specify integer coefficients are still under discussion.

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