【问题标题】:This condition will always return 'true' since the types 'number' and '{ id: number; }' have no overlap此条件将始终返回 \'true\',因为类型 \'number\' 和 \'{ id: number; }\' 没有重叠
【发布时间】:2022-11-09 00:34:24
【问题描述】:

我正在做我的应用程序的上下文,我有这个错误“这个条件将总是返回 'true',因为类型 'number' 和 '{ id: number; }' 没有重叠”,我正在练习打字稿,但我有不知道我该如何解决,这是我的代码。

import { Note, NoteState } from "../interfaces/interfaces";

type NoteActions =
    | { type: 'addNote', payload: Note }
    | { type: 'toggleInteresting', payload: { id: number } }
    | { type: 'changeState', payload: string }
    | { type: 'deleteNote', payload: { id: number } }

export const NoteReducer = (state: NoteState, action: NoteActions): NoteState => {

    switch (action.type) {
        case 'addNote':
            return {
                ...state,
                notes: [...state.notes, action.payload]
            }

        case 'toggleInteresting':
            return {
                ...state,
                notes: state.notes.map(({ ...note }) => {
                    if (note.id === action.payload.id) {
                        note.interesting = !note.interesting;
                    }

                    return note
                })
            }
        case 'changeState':
            return {
                ...state,
                active: action.payload
            }
        case 'deleteNote':
            return {
                ...state,
                ERROR
                <----notes: state.notes.filter(note => note.id != action.payload)--->
            }
        default:
            return state;
    }
}

这是我的界面:

export interface Note {
    id: number;
    description: string;
    title: string;
    interesting: boolean;
    created: string;
}

export interface NoteState {
    notesCount: number;
    notes: Note[];
    active: any;
}

【问题讨论】:

  • 你可能想要note.id !== action.payload.id,就像你在map下的toggleInteresting一样。
  • note.id != action.payload 左边是number,右边是{ id: number; }
  • 非常感谢您的帮助,我已经解决了

标签: reactjs typescript react-context


【解决方案1】:

您定义了操作{ type: 'deleteNote', payload: { id: number } } - 在这里您说有效负载应该是包含 id 的对象。

在这里,您尝试将有效负载对象与数字进行比较:
notes: state.notes.filter(note =&gt; note.id != action.payload)

看看您的 'toggleInteresting' 操作 - 您正在正确比较它:

notes: state.notes.map(({ ...note }) => {
  if (note.id === action.payload.id) {
    note.interesting = !note.interesting;
    }

    return note
  })

正确的条件应该是:
notes: state.notes.filter(note =&gt; note.id != action.payload.id)

【讨论】:

  • 感谢您的解释,现在该应用程序可以工作了
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 2021-05-06
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 2020-12-11
  • 2019-07-03
相关资源
最近更新 更多