Skip to content

[next/nightly] Incorrect _'obj.prop' is possibly 'undefined'._ Error in CFA with exactOptionalPropertyTypes and Optional-never PropertiesΒ #55566

Closed
@SlurpTheo

Description

@SlurpTheo

πŸ”Ž Search Terms

exactOptionalPropertyTypes

πŸ•— Version & Regression Information

  • This changed between versions typescript@5.2 and typescript@5.3.0-dev.20230816 (still happening in typescript@5.3.0-dev.20230825)

⏯ Playground Link

https://www.typescriptlang.org/play?exactOptionalPropertyTypes=true&ts=5.3.0-dev.20230825#code/KYDwDg9gTgLgBAMwK4DsDGMCWEVwLYCGmKAFAQFxwDOMUxA5gNoC6cAPnKgCbALHBcAlHADeAWABQcaXDQ4acAF5wAvHAJwA9Jsky9cAPyj1cAL6790yiLgAjSowBEMABbAowR61MBuSRelFADoNbQD9I2CCIJgIAGVaBhJBcL1KYNsY+MSUemSfLU04GCoAAQBWIIBmOHcoaDgcOAADDOa4Nw84AHc3XGbQAgwAeTAsHAIAGwAFerB3GABPABVF+ap2zCpalAJbSYF-KRltHugAawBaAnruOABiAEZwuRQFRQB1C4BBW5QuazqSg0Oi5FgAGjsBko3F4-C4ZnYxns1ByTGYkII0M4-zhKAEiLUij8x0CXyg51+EG4IUKqRkkXJlL+XBCWQSoLyKVJ+nSTKpNMysQ5SUEJPCp26F2uLIeACZwo4CI44MQlIVii4tqrtgAqXXDAByABkAJr6kwANymmARUopN2p-x6fRagxGY2wuxmcwWKzWwA2cH1AEk4hbgLt9oceXpImzhWjkvSrEogkLspz8pJzBIgA

πŸ’» Code

export function main(a: string[] | undefined) {
    const z = a //
        ? { a }
        : { b: ["there"] };

    z.a //
        ? z.a.toString()
        : z.b.toString(); // ts@5.3 error on `z.b` here when `exactOptionalPropertyTypes` is enabled

    // work-around #1
    const zWorkAround: { a: string[], b?: undefined } | { b: string[], a?: undefined } = z;
    zWorkAround.a //
        ? zWorkAround.a.toString()
        : zWorkAround.b.toString();

    // work-around #2
    "a" in z // this is **ONLY** a valid workaround when `exactOptionalPropertyTypes` **IS** enabled
        ? z.a.toString()
        : z.b.toString();
}

πŸ™ Actual behavior

Errors in code

'z.b' is possibly 'undefined'.

πŸ™‚ Expected behavior

Try any pervious version (I checked back to typescript@4.0) and the CFA from the !!z.a branch works fine.

Additional information about the issue

An interesting little problem/tidbit back to typescript@4.4 is this IntelliSense:

  • image

Why is a optional in the "a" in zWorkaround2 branch?

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions