Home > other >  Typescript complains about a property not being there but it is there
Typescript complains about a property not being there but it is there

Time:03-15

I have this component called PianoMK1Props, it accept some props, one of the props is an object called recording which looks like this(the state variable):

  const [recording, setRecording] = useState({
    mode: "RECORDING",
    events: [],
    currentTime: 0,
    currentEvents: []
  })  

That recording variable is passed to the component like so

          <PianoMK1
            recording={recording}
          />

And the PianoMK1 component has the types declared like so:

interface Recording {
    mode: string;
    events: number[];
    currentTime: number;
    currentEvents: number[];
}

type PianoMK1Props = {
  noteRange?: any,
  playNote?: any,
  stopNote?: any,
  onPlayNoteInput?: any,
  onStopNoteInput?: any,
  width?: any,
  disabled?: any,
  keyboardShortcuts?: any,
  recording?: Recording,
};
 
function PianoMK1({
  noteRange,
  playNote,
  stopNote,
  onPlayNoteInput,
  onStopNoteInput,
  width,
  disabled,
  keyboardShortcuts,
  recording,
}: PianoMK1Props) {



 const { mode, currentEvents } = recording;
 // HERE IT throws the error: Property 'mode' does not exist on type 'Recording | undefined'.
 ...
}

You can clearly see that the interface Recording has is an object with the type mode, Yet typescript says Property 'mode' does not exist on type 'Recording | undefined'

What is wrong here?

Thanks.

CodePudding user response:

Because recording can be undefined use

const { mode, currentEvents } = recording || {} ;
  • Related