Skip to content

Instantly share code, notes, and snippets.

@tataue
Last active August 11, 2021 09:43
Show Gist options
  • Save tataue/cf447782d30e451c9bacf07310ca6a1b to your computer and use it in GitHub Desktop.
Save tataue/cf447782d30e451c9bacf07310ca6a1b to your computer and use it in GitHub Desktop.
[ts-xor] xor typescript #ts #typescript
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" };
@tataue
Copy link
Author

tataue commented Jul 4, 2021

ori

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment