0

我正在做我的应用程序的上下文,我有这个错误“这个条件将总是返回 '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;
}

4

1 回答 1

1

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

在这里,您尝试将有效负载对象与数字进行比较:
notes: state.notes.filter(note => 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 => note.id != action.payload.id)

于 2022-03-02T00:05:57.510 回答