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.
Is there a way to type an object in a way that its keys can only be strings that match a given Regex?
No.
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
}
Regex-validated string types that would let you properly specify integer coefficients are still under discussion.