I need to create an object where the fields are required to be of a specific type (CSSProperties
in this particular case, but ultimately I want a generic type).
Using an indexed type (or Record
) allows TypeScript to enforce the correct type for field values, leading to error messages if there are any misdefined contents. However, TypeScript loses track of explicitly defined fields, so referencing an undefined field will not trigger a compilation error and will result in returning undefined
.
export const simpleStyle = {
a: {
margin: 0,
},
b: {
margin: 0,
wibble: 'blah', // no compile error: BAD
},
}
const simpleA = simpleStyle.a;
// compiles with an error message: GOOD
// const simpleB = simpleStyle.wibble;
export type CssStyles = { [index: string]: CSSProperties };
export const typedStyle: CssStyles = {
a: {
margin: 0,
},
b: {
margin: 0,
// triggers a compile error: GOOD
// wibble: 'blah',
},
}
const typedA = typedStyle.a;
// does not produce a compilation error
const typedB = typedStyle.wibble;
What is the method to define this type in such a way that TypeScript considers references to undefined indexes as incorrect? The determination of "defined" should rely on the object's declaration content (avoiding the need to redefine all fields in a union or specify an explicit type).