亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

打字稿中可選道具類型檢查錯誤

打字稿中可選道具類型檢查錯誤

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 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號