对于打字稿我是新手,我很难弄清楚这个问题
当我尝试从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'.
但是,如果我只是直接访问sub属性,我可以“抑制”错误消息
const title = this.props.confirm && this.props.confirm.title;
但是我真的很想能够破坏道具,我该如何做到呢?
答案 0 :(得分:0)
如果您确定道具中存在confirm
,则可以使用!
运算符告诉类型检查器此信息
const title = this.props.confirm!.title;
const {
closeConfirm,
confirmOpen,
confirm
} = this.props;
if (confirm){
const {
title,
content,
onConfirm,
onDecline,
onClose,
...options
} = confirm
}
答案 1 :(得分:0)
这就是我最终这样做的方式-仍然感觉很奇怪,但是打字稿错误消失了
const {
closeConfirm,
confirmOpen,
} = this.props;
const {
title,
content,
onConfirm,
onDecline,
onClose = () => {},
...options
} = this.props.confirm!;