React Proptypes 联合类型断点给出错误

React Proptypes union type Breakpoint gives error

我无法为 material-ui Breakpoint 类型提供正确的 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 assertion

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,
}