How do you combine an index signature with specific, explicitly-named required properties?
Short answer
You can mix known properties with an index signature, but every explicitly-named property's type must be ASSIGNABLE to the index signature's value type, since the index signature effectively promises every property (named or not) conforms to that value type.
Advertisement
AModel answer
You can mix known properties with an index signature, but every explicitly-named property's type must be ASSIGNABLE to the index signature's value type, since the index signature effectively promises every property (named or not) conforms to that value type.
interface Config {
name: string; // must be compatible with the index signature's value type
[key: string]: string; // allows any other string-valued property too
}
const config: Config = { name: 'App', theme: 'dark', version: '1.0' };Real-world example
Modeling a configuration object with a few known required fields plus arbitrary additional string settings.
Likely follow-ups
- What compiler error occurs if a named property's type conflicts with the index signature's value type?
Related topics