Last active
August 15, 2022 01:30
-
-
Save hasparus/ba5c31f391310a73026fc5f0383f6266 to your computer and use it in GitHub Desktop.
lightweight sum type matching in typescript
This file contains 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
interface A { type: 'A', a: 10 }; | |
interface B { type: 'B', b: [11] }; | |
type AB = A | B; | |
type TypeOf<T extends { type: any }> = T extends { type: infer Type } ? Type : never; | |
type Cases<T extends { type: any }, R> = { | |
[P in TypeOf<T>]: (val: Extract<T, { type: P }>) => R | |
} | |
function match<T extends { type: string }, C extends Cases<T, any>>( | |
value: T, | |
cases: C | |
): ReturnType<C[keyof C]> { | |
return cases[value.type as TypeOf<T>](value as Extract<T, { type: string }>); | |
} | |
const ab: AB = { type: 'A', a: 10 } as any; | |
const _: 10 | 11 = match(ab, { | |
A: a => a.a, | |
B: b => b.b[0] | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=2&pc=1#code/C4TwDgpgBA0hJQLxQM7AE4EsB2BzKAPlNgK4C2ARhOgNwBQdokUAyprpgDYA8MUEAD2ARsAExSx4AGigAVfkJHjUGHPmRoseAHxIoAbzpQoAbQD6UHLAC6ALjn0AvvUbhostwHkAZrwXCxCTgQGXlBAOU2Dh4YbV1kWRMYaxcmaABhAEMUCBQ-cKUg6Tl-QqgAJQgAYwB7dFFeGUzsEG0ZcviDI1MABUtsOS9fGFDtOygACgA3TM57AFEhdEyq4G5Zduq6hpGoHriASiRdcqcXbxJsVcwagbJM4CqAC3zFQMlWiYBreHsYI8MxnQEGAJHQAwuV2ANzuD2eAEZ1qV3lEuLw2lB0sjlFkcnldhsoM1WtoJt1jDNOCQIPYNuSoFVsrl7Olugd7JVQeCPJBuOkTD8QDVvJjrLpAcYoMCuQNGXiTJTqQL4NZrNNZtSiRJFhgVmtCZVavVGiotLhDvRjM46I4GLVsGgoPdHk8edBkM7nhMAERpb0HFwAekDUGEaAYOGE6G8K2gAEEusY0vZvXHvZaifZ4QAGJx0SPUGNVaAAIUTobcKZL6e6FHsJnh8JSNtczDjZeQCaIJZc9sdmTrUHben0FcgKbTTSz2agji1RJaQZDfeAUDM08IUEbdBXa70ntdbgmA5kErj9kyxyJADpMlJuiX7BQrxRrxQTNnrDaA3bbo6DzAOCiPucJPBMADkXxAeBP75tgUZFtAAAiNT4BKxhQWI9jgShuDgfekrEJkZA0qaagZsYFCZOgXwTOyZF4HmcEIbGmIPOWGFAdhWTAOBFFESR9iaOR9IkTUADudFCaojEtjuf6rpAwD2Lhm48SOUCYaI3EPPhAmkeBABiVLeN4IB6WJ4n2HRV7gQAshAEkAITgbO87Er2ClrvCIEuoBYgTEpp70jx1mMsARyILo4XXpZdEEZKuHWaIqGRboKW4G+1G0Qc350EAA