Skip to content

Map derived from discriminated union has wrong type when discriminator property has the same value #37859

@chenlijun99

Description

@chenlijun99

TypeScript Version: 3.8.3

Search Terms:

  • map from discriminated union same key
  • discriminated union same key

Expected behavior:

CatMap should have type

type CatMap = {
    cat: TerrestrialCat[] | AlienCat[];
}

Actual behavior:

CatMap has type

type CatMap = {
    cat: AlienCat[];
}

Related Issues:

Code

enum TerrestrialAnimalTypes {
    CAT = "cat",
};

enum AlienAnimalTypes {
    CAT = "cat",
};

type AnimalTypes = TerrestrialAnimalTypes | AlienAnimalTypes;

interface TerrestrialCat {
    type: TerrestrialAnimalTypes.CAT;
    address: string;
}

interface AlienCat {
    type: AlienAnimalTypes.CAT
    planet: string;
}

type Cats = TerrestrialCat | AlienCat;

// type A = TerrestrialCat | AlienCat
type A = Extract<Cats, { type: "cat" }>;

/*
 * type CatMap = {
 *   cat: AlienCat[];
 * }
 */
type CatMap = {
    [V in AnimalTypes]: Extract<Cats, { type: V }>[]
};
Output
"use strict";
var AnimalTypes;
(function (AnimalTypes) {
    AnimalTypes["CAT"] = "cat";
})(AnimalTypes || (AnimalTypes = {}));
;
Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "useDefineForClassFields": false,
    "alwaysStrict": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "downlevelIteration": false,
    "noEmitHelpers": false,
    "noLib": false,
    "noStrictGenericChecks": false,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "esModuleInterop": true,
    "preserveConstEnums": false,
    "removeComments": false,
    "skipLibCheck": false,
    "checkJs": false,
    "allowJs": false,
    "declaration": true,
    "experimentalDecorators": false,
    "emitDecoratorMetadata": false,
    "target": "ES2017",
    "module": "ESNext"
  }
}

Playground Link: Provided

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions