Skip to content

3.9 regression: TS2322 error around assignment of an inferred intersection to a union  #38542

Closed
@RomainMuller

Description

@RomainMuller

TypeScript Version: 3.9.2, 4.0.0-dev.20200512

Search Terms: TS2322, "is not assignable to type"

Code

import * as reflect from 'jsii-reflect'; // Version ^1.5.0

export type ApiElement = reflect.Type | reflect.TypeMember | reflect.EnumMember;

export interface Data {
  readonly element: ApiElement;
}

// Note: reflect.Method and reflect.Initializer both directly or indirectly implement reflect.TypeMember
export function doSomething<T extends (reflect.Method | reflect.Initializer)>(element: T): Data {
  if (reflect.Method.isMethod(element)) {
    // Type 'T & Method' is not assignable to type 'Type'.
    return { element };
  }
  if (reflect.Initializer.isInitializer(element)) {
    // Type 'T & Initializer' is not assignable to type 'Type'.
    return { element };
  }
  // Type checking absolutely fine - why'd previous ones not?
  return { element };
}

Expected behavior:
It should work like it did in TypeScript 3.8

Actual behavior:

$ tsc --build
lib/index.ts:13:14 - error TS2322: Type 'T & Method' is not assignable to type 'ApiElement'.
  Type 'T & Method' is not assignable to type 'Type'.

12     return { element };
                ~~~~~~~

  lib/index.ts:6:12
    6   readonly element: ApiElement;
                 ~~~~~~~
    The expected type comes from property 'element' which is declared here on type 'Data'

lib/index.ts:17:14 - error TS2322: Type 'T & Initializer' is not assignable to type 'ApiElement'.
  Type 'T & Initializer' is not assignable to type 'Type'.

16     return { element };
                ~~~~~~~

  lib/index.ts:6:12
    6   readonly element: ApiElement;
                 ~~~~~~~
    The expected type comes from property 'element' which is declared here on type 'Data'

Playground Link: I stored my repro at https://github.com/RomainMuller/TypeScript39-Bug (public)

Related Issues: It appears likely related to the breaking change in #37195 (but not certain)

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