redux 类型“WriteableDraft”上不存在属性“id< Note>|可写草稿〈{}>

insrf1ej  于 2023-01-30  发布在  其他
关注(0)|答案(1)|浏览(113)

我正在将我的ReactJS / Redux Toolkit应用程序转换为Typescript。我面临的一个问题是我无法获取状态对象的属性:

const useUpdatedData = (
  setNoteDescription: React.Dispatch<React.SetStateAction<string>>,
  setNoteData: React.Dispatch<
    React.SetStateAction<
      {
        fileName: string
        content: string
      }[]
    >
  >
) => {
  const { note } = useAppSelector((state) => state.notes)
  const { noteId } = useParams()

  useEffect(() => {
    if (noteId && noteId === **note.id**) {
      const filesData = filesObjectToArray(**note?.files**)
      const filesArray = filesData?.map((file) => {
        return {
          fileName: **file.filename**,
          content: **file.content**,
        }
      })

      setNoteDescription(note?.description)

      setNoteData(filesArray)
    }
  }, [noteId])
}

我用**突出显示了它们。
界面如下所示:

export interface Note {
  url: string
  id: string
  public: boolean
  created_at: string
  updated_at: string
  description: string
  files: {
    filename: {
      filename: string
      content: string
    }
  }
  owner: {
    login: string
    id: string
    avatar_url: string
  }
}

这是初始状态:

interface NoteState {
  notes: Note[] | []
  userNotes: Note[] | []
  note: Note | {}
  searchedNote: Note | {}
  snackbar: {
    message: string
    type: string
    isOpen: boolean
  }
  forks: number
  deletedNote: string | null
  isSuccess: boolean
  isLoading: boolean
  isError: boolean
  isSearchError: boolean
  isStarred: boolean | undefined
  isForked: boolean | undefined
  isCreated: boolean
  isUpdated: boolean
  message: string | undefined
}

const initialState: NoteState = {
  notes: [],
  userNotes: [],
  note: {},
  searchedNote: {},
  snackbar: { message: "", type: "success", isOpen: false },
  forks: 0,
  deletedNote: null,
  isSuccess: false,
  isLoading: false,
  isError: false,
  isSearchError: false,
  isStarred: false,
  isForked: false,
  isCreated: false,
  isUpdated: false,
  message: "",
}

显然,id属性存在于接口中,那么为什么它说它不存在呢?

s6fujrry

s6fujrry1#

note可以是Note | {},即Note或空对象。TypeScript不允许您访问id属性,因为它可能不存在。
可以通过添加另一个检查'id' in note来实现这一点,这将把类型缩小到Note,然后可以访问.id

if (noteId && 'id' in note && noteId === note.id) {

相关问题