![](/img/trans.png)
[英]TS2339: property height does not exist on '{}', when destructuring possibly undefined object
[英]Getting a TS2339 error with optional property declaration when destructuring
作為打字稿的新手,我很難搞清楚這一點
當我嘗試從redux存儲中構造一個可選屬性(它是一個對象)時,我得到了TS2339錯誤
這是打字稿聲明
export interface CoreState {
// readonly confirm?: CoreConfirm;
readonly confirm?: {
title: string
readonly content: string | React.ReactNode
readonly confirmText: string
readonly declineText: string
onConfirm(): void
onDecline(): void
onClose(): void
};
}
然后我試着像這樣去解構它
const {
closeConfirm,
confirmOpen,
confirm: {
title,
content,
onConfirm,
onDecline,
onClose,
...options
},
} = this.props;
但是我確認它們的所有子屬性都有這個錯誤(比如標題,內容等)
Property 'title' does not exist on type '{ title: string; readonly content: ReactNode; readonly confirmText: string; readonly declineText: string; onConfirm(): void; onDecline(): void; onClose(): void; } | undefined'.
但是,如果我只是直接訪問子屬性,我可以“抑制”錯誤消息
const title = this.props.confirm && this.props.confirm.title;
但是,我真的希望能夠解構道具,我怎么能做到這一點?
如果你確定在道具中存在confirm
,那么你可以告訴typechecker使用這個信息!
操作者
const title = this.props.confirm!.title;
const {
closeConfirm,
confirmOpen,
confirm
} = this.props;
if (confirm){
const {
title,
content,
onConfirm,
onDecline,
onClose,
...options
} = confirm
}
這就是我最終做到這一點 - 仍然感覺不穩定但打字稿錯誤消失了
const {
closeConfirm,
confirmOpen,
} = this.props;
const {
title,
content,
onConfirm,
onDecline,
onClose = () => {},
...options
} = this.props.confirm!;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.