简体   繁体   中英

React typescript props not showing as possibly defined, even when I use '?' optional operator and '| undefined'

My linter seems to have stopped flagging possibly undefined properties passed into my React components. For example:

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

If I try to access prop1 within my component, I get no linter errors. But I do when the code is compiled if the disabledObject is undefined . I'm sure it used to work fine when I used the ? operator, or specified with | undefined| undefined .

I would have expected to see (parameter) disabledObject: BooleanTeeTypeObj | undefined (parameter) disabledObject: BooleanTeeTypeObj | undefined here instead.

截屏

All of my other linting seems to be working for typescript still. Can anyone think what's happening?

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
    }

This is because you have strictNullChecks: false . When it is set to false typescript ignores null and undefined entirely and BooleanTypeObject | undefined BooleanTypeObject | undefined is equivalent to BooleanTypeObject . If you want typescript to shown an error, you need to set it to strictNullChecks: true https://www.typescriptlang.org/tsconfig#strictNullChecks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM