Skip to content

Instantly share code, notes, and snippets.

@inoyakaigor
Created December 13, 2019 15:36
Show Gist options
  • Save inoyakaigor/a7ddca413753c4a3460544348f13f1e9 to your computer and use it in GitHub Desktop.
Save inoyakaigor/a7ddca413753c4a3460544348f13f1e9 to your computer and use it in GitHub Desktop.
Typescript XOR type error
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
// this type is NOT work as expected
type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;
// this type is work as expected
type XOR<T, U> = (T | U) extends Object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;
interface IValueWillChange<T> {
object: any;
type: "update";
newValue: T;
}
type xorType = XOR<{all?: any}, string>
function calculateRelativeStatsTotals(
change: IValueWillChange<xorType>
): IValueWillChange<xorType> {
var newValue = change.newValue
var object = { a: 1 }
var type = 'update' as 'update'
// there typescript compilator show an error for first variant of XOR type
if (newValue.all) {
console.log(1)
}
return {
newValue,
object,
type
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment