Reputation: 95
Being new to typescript i am having trouble figuring this out
When i try to destructure an optional property (which is an object) from redux store i get the TS2339 error
This is the typescript declaration
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
};
}
I then try and destructure it like so
const {
closeConfirm,
confirmOpen,
confirm: {
title,
content,
onConfirm,
onDecline,
onClose,
...options
},
} = this.props;
But i get this error on all them sub properties on confirm (like title, content etc)
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'.
However if i just access the sub property directly i can 'supress' the error messages
const title = this.props.confirm && this.props.confirm.title;
However i would really like to be able to destructure the props, how can i accomplish that?
Upvotes: 0
Views: 1023
Reputation: 95
This is how i ended up doing it - still feels wonky but the typescript errors are gone
const {
closeConfirm,
confirmOpen,
} = this.props;
const {
title,
content,
onConfirm,
onDecline,
onClose = () => {},
...options
} = this.props.confirm!;
Upvotes: 0
Reputation: 895
If you are sure confirm
exists in props then you can tell the typechecker this info using !
operator
const title = this.props.confirm!.title;
const {
closeConfirm,
confirmOpen,
confirm
} = this.props;
if (confirm){
const {
title,
content,
onConfirm,
onDecline,
onClose,
...options
} = confirm
}
Upvotes: 1