Skip to content

Instantly share code, notes, and snippets.

@danmt
Last active September 19, 2023 13:22
Show Gist options
  • Save danmt/c53716047106cbd5e04185128c160a2f to your computer and use it in GitHub Desktop.
Save danmt/c53716047106cbd5e04185128c160a2f to your computer and use it in GitHub Desktop.
Create a Mapped Type from a Discriminated Union
// Union method to create a mapped typed from a discriminated union
export type UnionBy<
Key extends string,
Value extends string,
Base,
Map extends Record<Value, object | null>
> = {
[TValue in keyof Map]: {
[key in Key]: TValue;
} & (Map[TValue] extends null ? Base : Base & Map[TValue]);
}[keyof Map & Value];
// Example usage:
export interface BugStatusMap {
reported: { reportedDate: Date };
inProgress: { startDate: Date };
fixed: { fixDate: Date };
}
export interface BugBase {
bugId: string;
bugDescription: string;
}
export type Bug = UnionBy<'status', keyof BugStatusMap, BugBase, BugStatusMap>;
const bug = {} as Bug;
if (bug.status === 'reported') {
// bug.reportedDate exists.
} else if (bug.status === 'inProgress') {
// bug.startDate exists.
} else if (bug.status === 'fixed') {
// bug.fixDate exists.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment