Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript throwing an error for the wrong type even when the type is right

I am using a react youtube package for the first time and I am trying to embed and customise youtube player in a react component:

const options = {
  height: 'auto',
  width: '100%',
  playerVars: {
    // https://developers.google.com/youtube/player_parameters
    controls: 0
  }
}

From the documentation I can see that I am using the right paramaters, but if I try to pass them like this:

<YouTube videoId="xyQ5qD-u-J7" opts={options} ref={videoElement}/>

But, typescript is throwing an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TS2769: No overload matches this call.   Overload 1 of 2, '(props: YouTubeProps | Readonly<YouTubeProps>): YouTube', gave the following error.     Type '{ height: string; width: string; playerVars: { controls: number; }; }' is not assignable to type 'Options'.       The types of 'playerVars.controls' are incompatible between these types.         Type 'number' is not assignable to type '0 | 2 | 1 | undefined'.   Overload 2 of 2, '(props: YouTubeProps, context: any): YouTube', gave the following error.     Type '{ height: string; width: string; playerVars: { controls: number; }; }' is not assignable to type 'Options'.

How is that possible, I am passing a right value for controls 0 and the right type, why is then Typescript throwing an error?
I have tried to import an Options interface:

import YouTube, {Options} from 'react-youtube'

But, then I got an error:

ESLint: Options not found in 'react-youtube'(import/named)

How can I fix this?

>Solution :

If you hover over options you see that typescript has inferred controls’ type as number.

The way typescript sees options, is that the value of controls can always be changed.

While it should be '0 | 2 | 1 | undefined' and not number, if you want to pass to as props.

There are a few ways to pass type checker, for example:

const options = {
  height: 'auto',
  width: '100%',
  playerVars: {
    // https://developers.google.com/youtube/player_parameters
    controls: 0
  }
} as const

options is now read-only and the the value of controls is guaranteed to always be the value of its definition (0).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading