gpt4 book ai didi

reactjs - 即使类型正确, typescript 也会因类型错误而抛出错误

转载 作者:行者123 更新时间:2023-12-02 18:25:31 27 4
gpt4 key购买 nike

我正在使用 react youtube package我第一次尝试在 React 组件中嵌入和自定义 YouTube 播放器:

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

从文档中我可以看到我使用了正确的参数,但是如果我尝试像这样传递它们:

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

但是, typescript 抛出错误:

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'.

这怎么可能,我为控件 0 传递了正确的值和正确的类型,为什么 Typescript 会抛出错误?我尝试导入选项界面:

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

但是,然后我得到了一个错误:

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

我该如何解决这个问题?

最佳答案

如果将鼠标悬停在选项上,您会看到 typescript 已将控件类型推断为数字

typescript 看待选项的方式是,控件的值总是可以改变的。

虽然它应该是'0 | 2 | 1 |如果您想作为 props 传递,则 undefined' 而不是 number

有几种方法可以通过类型检查,例如:

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

options 现在是只读的,并且控件的值保证始终为其定义的值 (0)。

关于reactjs - 即使类型正确, typescript 也会因类型错误而抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70291675/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com