首页 > 解决方案 > 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)

标签: reactjstypescriptmaterial-uireact-proptypesunion-types

解决方案


问题

当你这样做时:

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

推荐阅读