Typescript: Destructing doesnt allow for discriminated union

Created on 23 Nov 2020  路  3Comments  路  Source: microsoft/TypeScript

TypeScript Version: 4.1.0-beta

Code

function generate(who: string): {json: true, body: {hello: string}} | {json: false, body: string} {
    return {json: true, body: {hello: who}}
}

const {body, json} = generate('world');

if (json) {
    body // should give you auto-complete, for `.hello`
} else {
    body // should be a string, thus giving `includes` as an example
}

Issue
As you'll find from the code example, body on line 8 doesnt autocomplete with .hello

Compiler Options

{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": 2,
    "target": "ES2017",
    "jsx": "React",
    "module": "ESNext"
  }
}

Playground Link: Provided

Duplicate

Most helpful comment

Sometimes issues are academic speak that I have no clue if it's even the same thing! Thanks for the "duplicate" advice, I shall subscribe to that issue. Maintainers feel free to close this perhaps.

All 3 comments

Duplicate of #12184.

Sometimes issues are academic speak that I have no clue if it's even the same thing! Thanks for the "duplicate" advice, I shall subscribe to that issue. Maintainers feel free to close this perhaps.

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

siddjain picture siddjain  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments

blendsdk picture blendsdk  路  3Comments

Roam-Cooper picture Roam-Cooper  路  3Comments

manekinekko picture manekinekko  路  3Comments