Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write an interface with base value and unknown amount of dynamic properties?

I have an object structure which could be as follows:

const myObj = {
  callback : ( val : boolean ) => concole.log( val ),
  string1  : 'foo',
  string2  : 'bar',
  string3  : 'bla',
  // eventually string4, string5 etc.
}

Is there a way to define an interface where the object has an optional property callback and optional properties string + num?

Like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

interface MyInterface {
  callback                                ?: ( val ?: boolean ) => void;
  [ ( must be "string" + num ) : string ] ?: string
} 

So the only allowed props would be callback followed by string1, string2 and so forth wit no limit like string200.

Is this possible?

>Solution :

We can now use template literal types as keys in index signatures:

interface MyInterface {
    callback?: (val?: boolean) => void;
    [key: `string${bigint}`]: string;
}

I’ve used bigint instead of number so only integers are allowed.

This allows keys like string1 and string123 but not string or string1.2 (or the cases @jcalz showed 😛).

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading