我希望能够创建一个泛型类型,该类型与一个数组一起工作,该数组接受两个相似的对象,但不是完全相等的,每件事都可以正常工作,直到我想要访问一个不在两个对象中的值(在本例中为gender属性).

// React state logic 
interface Client {
  name: string;
  clientId: string;
  weekId: string;
  gender: string;
}

interface Program {
  name: string;
  clientId: string;
  weekId: string;
  type: string;
}

export interface StateInterface {
data: (Program | Client)[];
}



//In component Issue 
const clientsArr = _globalContext.data.filter((el) => el.name === value);

// Error massage on gender Property 
/*Property 'gender' does not exist on type 'Client | Program'.
Property 'gender' does not exist on type 'Program'.*/
console.log(clientsArr[0].gender!)

推荐答案

这是正确的行为.此时typescript无法知道该值是Client还是Program.可以做的是添加一个属性,允许您缩小类型.下面是一个例子:

// Added `human` property just as an example, doesn't have to be a boolean
// You could do something like `type: "client"` and `type: "program"`, 
// it would work aswell
interface Client {
  human: true;
  name: string;
  clientId: string;
  weekId: string;
  gender: string;
}

interface Program {
  human: false;
  name: string;
  clientId: string;
  weekId: string;
  type: string;
}

然后,当你访问它时,你会判断你的辨别属性:

if(clientsArr[0].human){
  // At this point typescript can be sure that the property exists, so no error
  console.log(clientsArr[0].gender)
}

Typescript相关问答推荐

Typescript问题和缩减器状态不会在单击时添加用途.属性'状态和调度'不存在于userContextType类型上'|null'

错误:note_modules/@types/note/globals.d.ts:72:13 -错误TS 2403:后续变量声明必须具有相同的类型

如何根据参数的值缩小函数内的返回类型?

Angular 行为:属性类型从SignalFunction更改为布尔

如何使用WebStorm调试NextJS的TypeScrip服务器端代码?

为什么我的一个合成函数不能推断类型?

如何使所有可选字段在打印脚本中都是必填字段,但不能多或少?

如何使用模板继承从子组件填充基础组件的画布

如何在Angular 服务中制作同步方法?

为什么特定的字符串不符合包括该字符串的枚举?

如果判断空值,则基本类型Gaurd不起作用

推断集合访问器类型

如何创建由一个帐户签名但使用另一个帐户支付的Hedera交易

基于闭包类型缩小泛型类型脚本函数的范围

Select 类型的子项

我可以使用JsDocs来澄清Typescript实用程序类型吗?

导航链接不触发自定义挂钩

可以';t使用t正确地索引对象;联合;索引类型

我可以使用对象属性的名称作为对象中的字符串值吗?

具有枚举泛型类型的 Typescript 对象数组