Tvinga ett mönster på objektets nyckelnamn i TypeScript-typ


I TypeScript, är det möjligt att deklarera en typ som anger att dess egenskaper har ett visst mönster, till exempel att de alla slutar med tecknet w?

För detta exempel är här ett sådant objekt som skulle överensstämma med den typen:

{
    "250w": ...,
    "1024w": ...,
    "300w": ...
}

Föremålet nedan skulle inte uppfylla kraven (med exemplet som gavs ovan):

{
    "share": ...,
    "bound": ...,
    "cut": ...,
}

Jag tänkte på något i stil med:

interface MyCrazyType {
   [key ????]: any;
}

Svar #1

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

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

Svar #2

Med TypeScript 4.1 och mallbokstavstyper kan du till en begränsad grad. Du skulle kunna göra något som

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

Lekplatslänk

För ditt specifika fall skulle typen vara

type mMyCrazyType = Record<specialPattern,any>

Relaterade artiklar