简体   繁体   中英

Getting a TS2339 error with optional property declaration when destructuring

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?

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
}

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!;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM