My collection consists of objects that share a common structure:
type Option = {
label: string
value: string | number | null
}
type ElementObject = {
id: string
options: Option[]
}
type ElementArray = ElementObject[]
const array: ElementArray = [
{
id: 'cars',
options: [
{
label: 'One',
value: 1,
},
{
label: 'Two',
value: 2,
}
]
},
{
id: 'year',
options: [
{
label: '70',
value: '1970',
},
{
label: 'Unknown',
value: null,
}
]
}
]
Each object's options
array should have values of a specific type - either number
for the cars
object, or string
and null
for the year
object.
Is there a way to enforce more precise type safety than simply using a union type for the value property?
I've attempted to define a stricter type directly within the array definition, but TypeScript does not uphold this restriction as expected - it allows values of other types without raising an error:
const array: ElementArray = [
{
id: 'cars',
options: [
{
label: 'One',
value: 1,
},
{
label: 'Two',
value: 2,
}
] as {
label: string
value: number
}[]
},
{
id: 'year',
options: [
{
label: '70',
value: '1970',
},
{
label: 'Unknown',
value: null,
}
] as {
label: string
value: null | string
}[]
}
]