I have numerous data types, each with a common property called dataType
, and I am currently mapping each one to that specific value:
interface GroupData {
dataType: "group";
name: string;
people: PersonData[];
}
interface PersonData {
dataType: "person";
name: string;
email: string;
messages: MessageData[];
}
interface MessageData {
dataType: "message";
message: string;
timestamp: number;
}
interface DataTypeMap {
group: GroupData;
person: PersonData;
message: MessageData;
}
This method works for now, but it's quite manual. In my application, I deal with a large number of data types which tend to change frequently. I want to streamline this process by automating it further. Here's what I've attempted so far:
type DataType = GroupData
| PersonData
| MessageData;
type DataTypeMap = {
[(T in DataType)["dataType"]]: T;
};
Handling a single union of data types is simpler compared to mapping keys based on values, however, TypeScript does not support this approach. The following TS errors are popping up:
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.
Cannot find name 'T'.
'DataType' only refers to a type, but is being used as a value here.
From what I can gather, these issues stem from syntax errors. It seems like using in
with unions other than strings and applying bracket selectors in an index signature may be problematic.
Is there a way to map a collection of data types based on a shared property?