Can data be interpreted differently based on a 'type-field'?
I am currently loading data from the same file with known type definitions. The current approach displays all fields, but I would like to automatically determine which type is applicable without casting the type during runtime. It's not the ideal solution.
I'm unsure if I'm pushing TypeScript too far here and if this logic should instead reside in the loading/parsing process.
Current method
enum MyTypes {
TypeA = "A",
TypeB = "B",
}
type IData = {
type: MyTypes;
data: IDataAllTypes <---- force the type to be `IDataTypeA` if the type field is `TypeA`
}
type IDataAllTypes = IDataTypeA | IDataTypeB
type IDataTypeA = {
id: string
age: number
foo: string[]
}
type IDataTypeB = {
id: string
name: string
bar: string[]
}