当该值在所使用的接口之一中明显可用时,为什么IDE会给出此错误? 上下文操作的接口使用两个接口来指定调度操作中的一种数据类型.当我try 更新Reducer中的数据时,IDE显示此错误.

Property 'firstName' does not exist on type 'iCards | iSearch'. Property 'firstName' does not exist on type 'iCards'.

下面是上下文操作的接口以及用于创建它的接口.

interface iAction{
    type: 'search' | 'show all';
    payload: iSearch | iCards
}

interface iSearch {
    firstName: string;
    lastName: string;
    country: string;
}

interface iCards {
    searchText: string;
    searchParams: string[];
}

以下是减速器代码.

export default function CardsReducer(initialData: iInitialData, action: iAction) {
const data = structuredClone(initialData); <-- initialData.firstName is already set to an empty string
data.firstName = action.payload.firstName;  <--- IDE gives me the error here.
return data
}

名字在iSearch接口和iInitialData接口中,为什么它告诉我它不存在?

推荐答案

因为payload可能有也可能没有属性firstName,所以TypeScrip会给出一个错误.

如果-iSearchiCards都有firstName,那么它就不会抱怨了.

您可以通过将iAction接口重构为联合类型来修复此问题.就像这样:

interface iSearchAction {
  type: 'search';
  payload: iSearch;
}

interface iShowAllAction {
  type: 'show all';
  payload: iCards;
}

type iAction = iSearchAction | iShowAllAction;

interface iSearch {
  firstName: string;
  lastName: string;
  country: string;
}

interface iCards {
  searchText: string;
  searchParams: string[];
}

export default function CardsReducer(initialData: iInitialData, action: iAction) {
  const data = structuredClone(initialData);
  if (action.type === 'search') {
    /**
     * Here typescript already knows that payload is of type iSearch,
     * because if action's type is 'search', payload's type is 'iSearch' due to type narrowing
     * Read more about type guards.
     */
    data.firstName = action.payload.firstName;
  }
  return data;
}

附注:您在给出的示例中没有指定iInitialData的类型,我认为它没有问题.

Typescript相关问答推荐

TypScript中的算法运算式

在TypeScript中,除了映射类型之外还使用的`in`二进制运算符?

类型{...}的TypeScript参数不能赋给类型为never的参数''

在配置对象上映射时,类型脚本不正确地推断函数参数

如何正确地对类型脚本泛型进行限制

如何使用一个字段输入对象,其中每个键只能是数组中对象的id属性,而数组是另一个字段?

如何在TypeScrip中正确键入元素和事件目标?

如何判断对象是否有重叠的叶子并产生有用的错误消息

如何在编译时为不带常量的参数引发错误

缩小并集子键后重新构造类型

被推断为原始类型的交集的扩充类型的交集

一个打字类型可以实现一个接口吗?

基元类型按引用传递的解决方法

将带有样式的Reaction组件导入到Pages文件夹时不起作用

带投掷的收窄类型

回调函数中的TypeScrip类型保护返回Incorect类型保护(具有其他未定义类型的返回保护类型)

内联类型断言的工作原理类似于TypeScrip中的断言函数?

我的类型谓词函数不能像我预期的那样工作.需要帮助了解原因

有没有办法从不同长度的元组的联合中提取带有类型的最后一个元素?

从接口推断模板参数?