microsoft / microsoft/TypeScript

Cannot assign generic type aliases that should be equivalent.

Open
#40,312 8 comments 1 reaction 1 assignee View on GitHub

@weswigham is already working on this.

Since Sep 1, 2020.

Bug Domain: check: Variance Relationships
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Cannot assign generic type aliases that should be equivalent.

Simple test case:

export type Example<TData>
    = (data: TData | null | undefined) => string | null;

function foo<T>()
{
    let x: Example<T> = undefined!;
    let y: Example<T | null | undefined> = undefined!;

    y = x;

    let x1: (data: T | null | undefined) => string | null = undefined!;
    let y1: (data: (T | null | undefined) | null | undefined) => string | null = undefined!;

    y1 = x1
}

Note that 'x' is not assignable to 'y' with strictNullChecks on. It results in the error:

Type 'Example<T>' is not assignable to type 'Example<T | null | undefined>'.
  Type 'T | null | undefined' is not assignable to type 'T'.
    'T' could be instantiated with an arbitrary type which could be unrelated to 'T | null | undefined'.
      Type 'undefined' is not assignable to type 'T'.
        'T' could be instantiated with an arbitrary type which could be unrelated to 'undefined'.(2322)

This seems very strange though. Example is just a type alias, which shouldn't have an impact on assignability. If we simply expand the type alias, we get the x1/y1 case. In the expanded form the compiler allows this just fine.

Note: this was working in 3.3. It does not seem to work on 4.0. I'm not sure at what point it may have broken.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.