我正在写反应打字稿,并且可选道具类型检查有问题。下面是我的代码:
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
。任何人都知道如何解决此问题,谢谢。
更新:我认为问题来自 PropTypes.arrayOf(PropTypes.string)。 arrayOf 导致错误。
我的tsconfig.json
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"module": "commonjs",
"target": "es5",
"lib": ["es2015", "dom"],
"types": ["node", "jest"],
"jsx": "react",
"moduleResolution": "node",
"sourceMap": true,
"allowJs": false,
"strict": true,
"declaration": true,
"esModuleInterop": true
},
"exclude": ["src/**/__tests__/**"]
}
打字稿版本: "typescript": "^3.4.2"
答案 0 :(得分:0)
当可选值在打字稿中可能为undefined
或null
时,应准确设置可选值的类型。如果您处于strict
模式,则有两种方法可以解决这种情况:
1。设置undefined
和null
的类型
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__/**"]
}