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

149
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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