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:
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?
CodePudding user response:
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
).