In typescript, is it possible to declare a type stating that their properties have some given pattern, for example, they all end with the character w?
For this example, here is one such object that would comply with that type:
{
"250w": ...,
"1024w": ...,
"300w": ...
}
The following object would not comply (with the example given above):
{
"share": ...,
"bound": ...,
"cut": ...,
}
I was thinking of something like:
interface MyCrazyType {
[key ????]: any;
}
type MyCrazyType = {
[key: `${number}w`]: any
}
https://github.com/microsoft/TypeScript/pull/44512 https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html
With typescript 4.1 and template literal types you can to a limited degree. You could do something like
type alphaNumeric = 'a'|'b'|'c'|'d' //you can take this to the extreme of all letters and numbers
type specialPattern = `${alphaNumeric}${alphaNumeric}w` | `${alphaNumeric}w` //this is limited to less than 1000 combinations see https://github.com/microsoft/TypeScript/pull/40336
let a:specialPattern = 'ab' //typescript complains because it does not end with w
a = 'abw' //good
a = 'aw' //good
a = 'abcw' //bad - more than two characters in front of the w
Playground Link
For you specific case the type would be
type mMyCrazyType = Record<specialPattern,any>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With