Skip to content

Simple ternary inference issue with generics #27578

@jeremybparagon

Description

@jeremybparagon

TypeScript Version: 3.2.0-dev.20181004

Code

const f = <T>(a: number) => {
  const b: (T extends { } ? number : number) = a;
};

Expected behavior: Successful compilation

Actual behavior: I get the following error:

error TS2322: Type 'number' is not assignable to type 'T extends {} ? number : number'.

   const b: (T extends { } ? number : number) = a;
         ~

Playground Link: Link

Use case:
I wouldn't expect anybody to write the code above. Here's something more like my original example (link):

const f = <B extends true | false>(b: B, n: number): (true extends B ? number | null : number) => {
  if (b) {
    return null as true extends B ? null : never;
  }
  return n;
};

This gives the error

error TS2322: Type 'number' is not assignable to type 'true extends B ? number : number'.

   return n;
   ~~~~~~~~~

In this practical example, there is a workaround, changing the return type to number | (true extends B ? null : never). But it was hard for me to figure out what was making TypeScript unhappy, since this seemed too simple an inference for TypeScript to miss.

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