typescript - 如何抛出对象交集类型的语法错误?

标签 typescript

  • TypeScript 3.2.2
  • 有两种具有不同属性的类型:AB .
  • 我想接受AB ,但想在 the intersection type 上抛出错误两者中的一个。

例如:

type A = { a: number }
type B = { b: number }

var a: A = { a: 1, b: 1 }     //← Property 'b' is invalid. Fine.
var b: B = { a: 1, b: 1 }     //← Property 'a' is invalid. Fine.
var c: A | B = { a: 1, b: 1 } //← I expected to be an error because this value is
                              //  compatible with neither A nor B, but allowed.
var d: A & B = { a: 1, b: 1 } //← OK because this is the intersection type.

TypeScript Playground

我期望 A | B成为我想要的人,但事实并非如此。

我怎样才能接受AB ,但不是A & B

最佳答案

TypeScript 中的联合是包容性的,而不是排他性的。您可以像这样建立排它联合:

type ProhibitKeys<K extends keyof any> = { [P in K]?: never }
type Xor<T, U> = (T & ProhibitKeys<Exclude<keyof U, keyof T>>) |
  (U & ProhibitKeys<Exclude<keyof T, keyof U>>);

type A = { a: number }
type B = { b: number }
var a: Xor<A, B> = { a: 1 }; // okay
var b: Xor<A, B> = { b: 1 }; // okay
var c: Xor<A, B> = { a: 1, b: 1 }; // error, 
// {a: number, b: number} not assignable to Xor<A, B>

关于typescript - 如何抛出对象交集类型的语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54121258/

相关文章:

javascript - Typescript 推断高阶函数的类型,该函数执行具有相同参数签名的可选函数参数

node.js - 类型错误 : Cannot read property 'EventEmitter' of undefined typescript nodejs

html - 我的问题是关于使用 Swiper http ://idangero. us 和 ionic 4

javascript - ES6 map : transform values

typescript - 推断重载函数的参数

angular - 我想在我的 Angular Web 应用程序中使用 Azure 应用服务 'Application settings' 变量

typescript - Vuex Typescript 我收到错误 "Member ' someMutation' implicitly has an 'any' type."in the Component.ts file

node.js - Node 情况下的 Typescript IOC

reactjs - firebase_compat_app__WEBPACK_IMPORTED_MODULE_0__.default.database 不是函数

angular - 错误类型错误 : Cannot assign to read only property 'stopImmediatePropagation' of object '[object Object]'