Typescript写对象类型时如何做到【或】的逻辑?

比如这里我的本意是让p为IProps1或IProps2,但这样写就变成联合类型了 [图片]
关注者
13
被浏览
7,403

7 个回答

之前也遇到过这样的问题

在线测试代码

interface IProps1 {
  firstName: string;
  lastName: string;
  age: number;
interface IProps2 {
  fullName: string;
  age: number;
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 Person = XOR<IProps1, IProps2>
// ================= test ==================
// correct
const p1: Person = {
  firstName: 'jack',
  lastName: 'spell',
  age: 12,
// correct
const p2: Person = {
  fullName: 'jack spell',
  age: 12,
// error
const p3: Person = {
  fullName: 'jack spell',
  age: 12,
  // error field
  firstName: 'jack',
// error
const p4: Person = {
  firstName: 'jack',
  lastName: 'spell',
  age: 12,
  // error field
  fullName: 'jack spell',