Skip to content

Instantly share code, notes, and snippets.

@inoyakaigor
Last active October 9, 2018 16:14
Show Gist options
  • Save inoyakaigor/bc285d8be0c58358d1faf931187a0565 to your computer and use it in GitHub Desktop.
Save inoyakaigor/bc285d8be0c58358d1faf931187a0565 to your computer and use it in GitHub Desktop.
Исключающее объединение типов в typescript

Взято отсюда microsoft/TypeScript#14094 (comment)

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