reactjstypescriptvisual-studio-codejavascript-intellisense

TypeScript optional properties not accepting undefined value


<MyCustomField
    type={props.type}

MyCustomField's type type definition:

type?: string;

props.type's type definition:

type?: string;

For some reason, I get this error: pic

It feels like I accidentally turned on some setting. My tsconfig:

{
    "compilerOptions": {
        "target": "es5",
        "lib": [
            "dom",
            "dom.iterable",
            "esnext"
        ],
        "allowJs": false,
        "skipLibCheck": true,
        "noImplicitAny": false,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react-jsx",
    },
    "include": [
        "src"
    ]
}

Edit: In addition, it compiles fine:

image

It's just that VSCode Intellisense doesn't like it.

Edit 2:

if (!clone[index].options) throw Error(`Data at index ${index}, ${optionIndex} doesn\'t have options`);
if (type === FieldDataTypeEnum.RadioButton) {
    clone[index].options.forEach(o => o.checked = false);
} else {
    clone[index].options[optionIndex].checked = true;
}

This also gives me an error saying that clone[index].options is possibly undefined, even though the if statement should neglect that:

image

But still compiles fine.


Solution

  • For me, VSCode was using the newest beta version of Typescript, and not the version I had declared in the workspace.

    This PR for their new beta version introduced some potential breaking changes, which is why you're seeing the errors you are. https://github.com/microsoft/TypeScript/pull/43947

    It introduces a new strict mode, --strictOptionalProperties. If you have "strict": true in your tsconfig, this new mode is enabled by default.

    Someone made a suggestion here that will likely help make this more clear. https://github.com/microsoft/TypeScript/issues/44403

    To sum it up, you are seeing an Intellisense issue in VSCode because VSCode is using a new version of Typescript that introduced breaking changes. If you change your VSCode Typescript version to match your workspace, you should be okay.