TypeScript 如何实现一个二选一的 interface?

TypeScript 如何约束一个 interface ,其中的两个值为2选一,
(不能都存在,也不能都不存在)

如下:

export interface MockData {
  name: string;
  nickName: string;
}

这个 interface 目前并不符合我的需求,我的需求是 name 或者 nickName 二选一,该如何改造?或者如何实现呢?

阅读 1.1k
3 个回答

如下:

export interface NameData {
  name: string;
}

export interface NickNameData {
  nickName: string;
}

export type Without<T,U> = {
  [P in Exclude<keyof T, keyof U>]?:never
}

export type NameOrNickName<T,U> = (Without<T,U> & U) | (Without<U,T> & T)

const myData1: NameOrNickName<NameData, NickNameData> = {
  name:'张子枫',
  nickName:'子枫'
} // fail

const myData2: NameOrNickName<NameData, NickNameData> = {
  name:'张子枫',
} // ok

const myData3: NameOrNickName<NameData, NickNameData> = {
  nickName:'子枫'
} // ok

等同于:


export interface NameDataNoNickName {
  name: string;
  nickName?:never;
}

export interface NickNameDataNoName {
  nickName: string;
  name?:never
}

export type NameOrNickName2 = NameDataNoNickName | NickNameDataNoName

const omyData1: NameOrNickName2 = {
  name:'张子枫',
  nickName:'子枫'
} // fail

const omyData2: NameOrNickName2 = {
  name:'张子枫',
} // ok

const omyData3: NameOrNickName2 = {
  nickName:'子枫'
} // ok

第一种方式比较优雅一点

用Union Types

export type MockData = {
  name: string;
} | {
  nickName: string;
};
推荐问题
logo
Microsoft
子站问答
访问
宣传栏