Skip to content

Generic index access on target type and return based on discriminated types do not work. #32698

Closed
@archfz

Description

@archfz

TypeScript Version: ^3.5.0

Search Terms: index access target type discriminated types

Code

interface TypeA {a: string; }
interface TypeB {b: string; }

class A implements TypeA {public a: string = ""; }
class B implements TypeB {public b: string = ""; }

enum Types {
  A= "a", B = "b",
}

interface TypeInterfaces {
  [Types.A]: TypeA;
  [Types.B]: TypeB;
}

function create<T extends Types>(type: T): TypeInterfaces[T] {
  if (type === Types.A) {
    return new A;
  } else if (type === Types.B) {
    return new B;
  }

  throw new Error();
}

Expected behavior:
The compiler knows with discriminated types exactly what it needs to return and there are no errors as in 3.4 or lower.

Actual behavior:
The compiler gives an error that we cannot assign the returned A or B to TypeA & TypeB regardless of the fact that we actually know for sure with discriminated types that we need to return either TypeA or TypeB.

Playground Link:
Try it on playground

Related Issues:
This issue was specifically introduced here for v3.5 #30769 by @ahejlsberg when it was decided to have the target type on index types as intersections.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions