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

我正在编写反应打字稿,并且对可选的道具类型检查有问题。下面是我的代码:


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。有谁知道如何解决这个问题,谢谢。


aluckdog
浏览 145回答 1
1回答

呼如林

undefined当可选值可能是打字稿或null打字稿时,您应该准确设置它们的类型。如果您处于strict模式下,针对这种情况有两种选择:undefined1.设置s和nulls的类型interface InputNumberProps {&nbsp; className?: undefined | string | (string | undefined | null)[];}&nbsp;&nbsp;2. 将您的更改tsconfig为跳过检查null和undefined:{&nbsp; &nbsp; "compilerOptions": {&nbsp; &nbsp; &nbsp; &nbsp; "allowSyntheticDefaultImports": true,&nbsp; &nbsp; &nbsp; &nbsp; "module": "commonjs",&nbsp; &nbsp; &nbsp; &nbsp; "target": "es5",&nbsp; &nbsp; &nbsp; &nbsp; "lib": ["es2015", "dom"],&nbsp; &nbsp; &nbsp; &nbsp; "types": ["node", "jest"],&nbsp; &nbsp; &nbsp; &nbsp; "jsx": "react",&nbsp; &nbsp; &nbsp; &nbsp; "moduleResolution": "node",&nbsp; &nbsp; &nbsp; &nbsp; "sourceMap": true,&nbsp; &nbsp; &nbsp; &nbsp; "allowJs": false,&nbsp; &nbsp; &nbsp; &nbsp; "strict": true,&nbsp; &nbsp; &nbsp; &nbsp; "strictNullChecks": false, // this will skip that checking&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; "declaration": true,&nbsp; &nbsp; &nbsp; &nbsp; "esModuleInterop": true&nbsp; &nbsp; },&nbsp; &nbsp; "exclude": ["src/**/__tests__/**"]}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript