Chris
Chris

Reputation: 2267

Typescript can't assign property after undefined check

I was reading through the MDN article for MediaDevices.getUserMedia() and they have a little polyfill example for browsers that are a bit special. You can find it here.

I'm using Typescript and i get some weird errors. I'm new to Typescript so I'm probably missing something. This part:

if (navigator.mediaDevices === undefined) {
  navigator.mediaDevices = {};
}

TS tells me that the reassignment of the mediaDevices property is an error because it is a read-only property or constant. But if it is undefined how can it be read-only? I'm confused.

I'm using Typescript 2.3.4 and the awesome-typescript-loader for Webpack.

Upvotes: 1

Views: 640

Answers (1)

Saravana
Saravana

Reputation: 40554

The issue is that navigator.mediaDevices is really read-only in browsers that implement it. So TypeScript is correct in indicating that you can assign to it.

However since you are using the polyfill for old browsers where navigator.mediaDevices can be undefined and TypeScript does not seem to understand that, you can just create an untyped copy of the navigator to add the polyfill:

let navigatorCopy = navigator as any;
if (navigatorCopy.mediaDevices === undefined) {
  navigatorCopy.mediaDevices = {};
}

Upvotes: 2

Related Questions