Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!