我正在将我的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属性存在于接口中,那么为什么它说它不存在呢?
1条答案
按热度按时间s6fujrry1#
note
可以是Note | {}
,即Note
或空对象。TypeScript不允许您访问id
属性,因为它可能不存在。可以通过添加另一个检查
'id' in note
来实现这一点,这将把类型缩小到Note
,然后可以访问.id
: