Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Impose some pattern over object key names in typescript type

Tags:

typescript

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;
}
like image 767
rslemos Avatar asked Sep 17 '25 03:09

rslemos


2 Answers

type MyCrazyType = {
    [key: `${number}w`]: any
}

https://github.com/microsoft/TypeScript/pull/44512 https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html

like image 113
matepal297 Avatar answered Sep 19 '25 19:09

matepal297


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>
like image 22
MacD Avatar answered Sep 19 '25 20:09

MacD