【问题标题】:React typescript props not showing as possibly defined, even when I use '?' optional operator and '| undefined'反应打字稿道具未显示为可能定义,即使我使用“?”可选运算符和 '|不明确的'
【发布时间】:2022-01-13 09:49:19
【问题描述】:

我的 linter 似乎已经停止标记传递给我的 React 组件的可能未定义的属性。例如:

    interface BooleanTypeObject {
        prop1: true
    }
    
    interface MyComponentProps {
        disabledObject?: BooleanTypeObject | undefined;
    }
    
    export function MyComponent({
        disabledObject
    }: MyComponentProps): ReactElement {
    ...
    }

如果我尝试在我的组件中访问 prop1,我不会收到任何 linter 错误。但是如果disabledObjectundefined,我会在编译代码时这样做。我确信当我使用 ? 运算符或使用 | undefined 指定时它可以正常工作。

我本来希望在这里看到(parameter) disabledObject: BooleanTeeTypeObj | undefined

我所有的其他 linting 似乎仍然适用于 typescript。谁能想到发生了什么?

tsconfig.json

    {
        "compilerOptions": {
            "target": "ES2018",
            "module": "commonjs",
            "checkJs": false,
            "jsx": "react",
            "sourceMap": true,
            "strict": false,
            "noImplicitAny": false,
            "noUnusedLocals": false,
            "noUnusedParameters": false,
            "allowSyntheticDefaultImports": true,
            "esModuleInterop": true,
            "skipLibCheck": true,
            "forceConsistentCasingInFileNames": true
    }

【问题讨论】:

  • 我之前没有见过声明为MyComponent({disabledObject}: MyComponentProps) 的组件道具。这是在试图解构道具吗?您是否尝试过使用传统的MyComponent(props: MyComponentProps)? (如果你愿意,你可以在组件函数内部解构)
  • 您的tsconfig.json 中是否启用了strictNullChecksstrict
  • @Алексей Мартинкевич 我已将 tsconfig 添加到帖子中。我严格设置为false。 strictNullChecks 是默认值。这应该重要吗?我觉得上周我正在使用相同的 tsconfig.json 设置,这不是问题。不过,我很可能是错的! (@DBS,我使用两种解构模式都很好。在这种情况下我的解构方式没有任何问题)

标签: javascript reactjs typescript


【解决方案1】:

这是因为你有strictNullChecks: false。当它设置为 false 时,打字稿完全忽略 nullundefined 并且 BooleanTypeObject | undefined 等效于 BooleanTypeObject。 如果您希望 typescript 显示错误,则需要将其设置为 strictNullChecks: true https://www.typescriptlang.org/tsconfig#strictNullChecks

【讨论】:

    猜你喜欢
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    相关资源
    最近更新 更多