My question is somewhat similar to this: TypeScript: How to create an interface for an object with many keys of the same type and values of the same type?.
I'm trying to create an interface for an object which can have several keys, all optional, but with the same type. In this object, there's also 1 unique key with a boolean value.
At first, I was trying to use a mapped index signature like:
const foo : {
[key in 'String 1' | 'String 2' | 'String 10']? : MyInterface
} = {}
However, with this approach, if I add another key like:
const foo : {
valid : boolean
[key in 'String 1' | 'String 2' | 'String 10']? : MyInterface
} = {}
TypeScript complains:
A mapped type may not declare properties or methods.
I can fix this by doing something like:
const foo : {
[key in 'string_1' | 'string_2' | 'string_10' | 'valid']? : boolean | MyInterface
} = {}
which works, but as you can see, it would also mean that foo.string_10
could also be a boolean
, which would be incorrect.
How can this be achieved?