Looking for a way to define an object with specific types for its keys and values? In this scenario, all keys of type string
should have values of type IModel
, except for the key "apple"
which should be of type IApple
.
If IApple
is a subtype of IModel
, the solution is quite straightforward. By using Record<string, IModel>
in conjunction with & {apple?: IApple}
, we ensure that all properties are of type IModel
, while also specifying that the apple
property must be of type IApple
, with the optionality denoted by ?
.
interface Itest {
propsA: Record<string, IModel> & {apple?: IApple}
}
For cases where IApple
and IModel
are unrelated types, things get more complex as the Record<string, IModel>
declaration covers all keys including apple
, resulting in an error "Property 'apple' is incompatible with index signature." To overcome this, it's necessary to specify that the value is IModel
for every key except for apple
.