Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard property name in interface? [duplicate]

Tags:

typescript

I know you can set a complete wildcard on an interface to allow any property you want in like:

interface ITest {
    [wildcard: string]: any;
}

But is there a way to have a wildcard match a pattern for the property name?

interface ITest {
    /EndOfKeyName$/: boolean;
    /^startOfKeyName/: string;
}

It doesn't have to be regex, I'm just trying to show an ideal scenario. I'm not sure this is possible though.

like image 765
m0ngr31 Avatar asked Sep 06 '25 03:09

m0ngr31


1 Answers

UPDATE FOR TS 4.4: Template Literal Types can now be used as below, as in the duplicate answer. The functionality is documented as "Symbol and Template String Pattern Index Signatures".

interface BoolsAndStrings {
    [key: `boolean${string}`]: boolean;
    [key: `string${string}`]: string;
}

typescript playground

If you attempt this in TypeScript 4.3 or prior, it will yield:

An index signature parameter type must be either 'string' or 'number'

like image 180
2 revsJeff Bowman Avatar answered Sep 08 '25 00:09

2 revsJeff Bowman