Looking to create an object that can have either primitives or objects as properties? Avoid pitfalls like the following:
const obj: DesiredType = {
correctProp1: 'string',
correctProp2: 123,
correctProp3: true,
wrongProp4: [1, 2, 3],
prop5: {
wrongProp1: () => {},
wrongProp2: [1, 2, 3],
correctProp3: 'other string'
}
}
Avoid using just Record<string, any>
, as it allows functions and arrays. Likewise, steer clear of structures like:
Record<string, string | number | boolean | Record<string, any>>
This setup is problematic because anything can appear on the second level.
One attempted solution involved:
type PrimitiveOrObject = string | number | boolean | Record<string, PrimitiveOrObject>; // ts(2456) type
DesiredType = Record<string, PrimitiveOrObject>;
However, this led to error ts(2456): Type alias "PrimitiveOrObject" circularly references itself.
Is there a method to define a type alias for objects containing primitives or objects like themselves?