Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

XOR #137

Open
mohsen1 opened this issue Apr 23, 2020 · 4 comments
Open

XOR #137

mohsen1 opened this issue Apr 23, 2020 · 4 comments

Comments

@mohsen1
Copy link

mohsen1 commented Apr 23, 2020

Is your feature request related to a real problem or use-case?

This is from a long discussion in TS issues

microsoft/TypeScript#14094

Describe a solution including usage in code example

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" };

Who does this impact? Who is this for?

A lot of APIs that return one or another responses.

@mohsen1
Copy link
Author

mohsen1 commented Apr 23, 2020

I'm curious to hear your perspective on this because you have a lot of experience with advanced generics

@blazery
Copy link

blazery commented May 5, 2020

Just curious, how is this any different from using the basic or '|'?
I know the difference between or and xor, but I don't see how this example would benefit from an XOR option.

Edit:
I played around with the example some more and now typescript bothers me.

type NameOnly = { name: string };
type FirstAndLastName = {firstname: string; lastname: string };
type Person =NameOnly | FirstAndLastName;

const person: Person = {firstname: 'john', lastname: 'doe', name: 'micheal'}

This should be valid TS
How is this in anyway what you would expect? Saying it is type A or B and than a weird mix of both is allowed!

@erkebek
Copy link

erkebek commented Oct 27, 2020

XOR is really useful type. Built-in union type allows a mix of two types, which is unwanted behavior.

@aweiu
Copy link

aweiu commented Nov 27, 2020

https://github.com/maninak/ts-xor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants