Search code examples
reactjstypescripttypeerroruse-refmediastream

A type error of "MediaStream" occurs when using "addTrack" in React's useRef


A type error occurs in myStreamRef.current inside addTrack.

const myStreamRef = useRef<MediaStream>();
...
if (myStreamRef.current) {
  myStreamRef.current.getTracks().forEach((track) => {
    peerRef.current?.addTrack(track, myStreamRef.current);
  });
}
Argument of type 'MediaStream | undefined' is not assignable to parameter of type 'MediaStream'.
Type 'undefined' is not assignable to type 'MediaStream'.

As shown below, if you eliminate the possibility of being undefined once more with the if statement, the error will no longer occur.
But I've already removed the possibility of being undefined with the outermost if statement, so I don't know why I have to regroup it.
If you know the answer or know of a cleaner way to solve this, please let me know. 🙏🙏🙏

const myStreamRef = useRef<MediaStream>();
...
if (myStreamRef.current) {
  myStreamRef.current.getTracks().forEach((track) => {
    if (myStreamRef.current) {  
      peerRef.current?.addTrack(track, myStreamRef.current);
    }
  });
}

Solution

  • This problem arose because the internal methods had to operate independently.