Last active
September 19, 2023 13:22
-
-
Save danmt/c53716047106cbd5e04185128c160a2f to your computer and use it in GitHub Desktop.
Create a Mapped Type from a Discriminated Union
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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