reactjs - React Proptypes联合类型断点给出错误
问题描述
我无法为 material-uiBreakpoint
类型提供正确的 proptype。
断点如下:export type Breakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl';
在我的 App.tsx 中,如果有以下代码:
import React, { FC } from 'react'
import PropTypes from 'prop-types'
import { Breakpoint } from '@material-ui/core/styles/createBreakpoints'
import withWidth from '@material-ui/core/withWidth'
interface IApp {
width: Breakpoint
}
const App: FC<IApp> = ({ width }) => {
// Code here
}
App.propTypes = {
width: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']).isRequired,
}
export default withWidth()(App)
这给了我以下错误:
Type '{ width: Validator<string>; }' is not assignable to type 'WeakValidationMap<IApp>'.
Types of property 'width' are incompatible.
Type 'Validator<string>' is not assignable to type 'Validator<Breakpoint>'.
Type 'string' is not assignable to type 'Breakpoint'.ts(2322)
解决方案
问题
当你这样做时:
App.propTypes = {
width: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']).isRequired,
}
TypeScript 将['xs', 'sm', 'md', 'lg', 'xl']
视为一个随机字符串数组,而不是您感兴趣的特定字符串。
解决方案(TypeScript 3.4+)
要将它们的类型缩小到由 定义的特定值Breakpoint
,请使用const 断言。
App.propTypes = {
width: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl'] as const).isRequired,
}
解决方案(TypeScript <3.4)
如果您运行的 TypeScript 版本早于 3.4,则可以通过在定义propTypes
.
const breakpoints: Breakpoint[] = ['xs', 'sm', 'md', 'lg', 'xl'];
App.propTypes = {
width: PropTypes.oneOf(breakpoints).isRequired,
}
推荐阅读
- php - How to print all possible variations without repetitions of array for given range?
- swift - MacOS SwiftUI,如何防止窗口关闭动作
- google-apps-script - eventdelete 功能需要替换以删除谷歌日历事件
- c++ - 2个独立伽马分布卷积的C++实现
- python - 如何读取 SYLK 中的西里尔字符(对于 MS Excel .the slk)?Py3.8
- html - 展开到顶部 html css
- reactjs - 如何使用 React Native 中的索引更新 useState 中的数组
- pine-script - 函数将 2 个值返回到全局变量
- c - 从文本文件中读取数据并将其添加到数组中
- angular - Angular 8 将服务导入接口/模块