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:
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?
CodePudding user response:
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