Last active
August 11, 2021 09:43
-
-
Save tataue/cf447782d30e451c9bacf07310ca6a1b to your computer and use it in GitHub Desktop.
[ts-xor] xor typescript #ts #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
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never }; | |
type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U; | |
type NameOnly = { is: "NameOnly", name: string }; | |
type FirstAndLastName = { is: "FirstAndLastName", firstname: string; lastname: string }; | |
type Person = XOR<NameOnly, FirstAndLastName>; | |
let person: Person; | |
person = { is: "NameOnly", name: "Foo" }; | |
person = { is: "FirstAndLastName", firstname: "Foo", lastname: "Bar" }; | |
let stringOrNumber: XOR<string, number>; | |
stringOrNumber = 14; | |
stringOrNumber = "foo"; | |
let primitiveOrObject: XOR<string, Person>; | |
primitiveOrObject= "foo"; | |
primitiveOrObject= { is: "NameOnly", name: "Foo" }; | |
primitiveOrObject= { is: "FirstAndLastName", firstname: "Foo", lastname: "Bar" }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ori