为了账号安全,请及时绑定邮箱和手机立即绑定

打字稿中可选道具类型检查错误

打字稿中可选道具类型检查错误

aluckdog 2023-07-20 09:50:19
我正在编写反应打字稿,并且对可选的道具类型检查有问题。下面是我的代码:import PropTypes from 'prop-types';interface InputNumberProps {  className?: string | string[];}  export const InputNumberAutosize = (props: InputNumberProps, ref: refType) => {     ...}const InputNumberAutoSizeComponent = React.forwardRef(InputNumberAutosize);InputNumberAutoSizeComponent.propTypes = {  className: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),};不知何故,当我这样声明时,我的打字稿会在 className 中抛出错误。这是错误:TS2322: Type 'Requireable<string | (string | null | undefined)[]>' is not assignable to type 'Validator<string | string[] | null | undefined>'.       Types of property '[nominalTypeHack]' are incompatible. Type '{ type: string | (string | null | undefined)[] | null | undefined; } | undefined' is not assignable to type '{ type: string | string[] | null | undefined; } | undefined'.     Type '{ type: string | (string | null | undefined)[] | null | undefined; }' is not assignable to type '{ type: string | string[] | null | undefined; }'.       Types of property 'type' are incompatible.        Type 'string | (string | null | undefined)[] | null | undefined' is not assignable to type 'string | string[] | null | undefined'.          Type '(string | null | undefined)[]' is not assignable to type 'string | string[] | null | undefined'.               Type '(string | null | undefined)[]' is not assignable to type 'string[]'.   Type 'string | null | undefined' is not assignable to type 'string'.       Type 'undefined' is not assignable to type 'string'.这看起来很奇怪,因为当我在文档中阅读时,prop-types应该是可选的并接受undefined。有谁知道如何解决这个问题,谢谢。
查看完整描述

1 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

undefined当可选值可能是打字稿或null打字稿时,您应该准确设置它们的类型。如果您处于strict模式下,针对这种情况有两种选择:


undefined1.设置s和nulls的类型


interface InputNumberProps {

  className?: undefined | string | (string | undefined | null)[];

}  

2. 将您的更改tsconfig为跳过检查null和undefined:


{

    "compilerOptions": {

        "allowSyntheticDefaultImports": true,

        "module": "commonjs",

        "target": "es5",

        "lib": ["es2015", "dom"],

        "types": ["node", "jest"],

        "jsx": "react",

        "moduleResolution": "node",

        "sourceMap": true,

        "allowJs": false,

        "strict": true,

        "strictNullChecks": false, // this will skip that checking 

        "declaration": true,

        "esModuleInterop": true

    },

    "exclude": ["src/**/__tests__/**"]

}


查看完整回答
反对 回复 2023-07-20
  • 1 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信