Skip to content

Can't call ((_: string) => T) | undefined when conditionally string extends T #43425

Closed
@jtbandes

Description

@jtbandes

Bug Report

I am trying to make a generic callback function (_: string) => T, that is allowed to be optional (undefined) only when T is string. (Specifically, I chose string extends T because TS doesn't seem to provide exact equality for conditional types, and I want the default value to be (x: string) => x.)

The initial way I wrote this was string extends T ? ((value: string) => T) | undefined : (value: string) => T, but I found I was unable to (conditionally) call the function. The error seems to stem from TS treating the type as (value: T & string) => T, which prevent me from passing in a string literal.

image

I found a workaround that allows me to call the function: ((value: string) => T) | (string extends T ? undefined : never) (which I believe should be exactly equivalent, though let me know if this is wrong). However, this too is broken in the latest nightly, seemingly because of how NonNullable is being distributed over |:

Screen Shot 2021-03-29 at 12 17 07 PM

🔎 Search Terms

generic extends function parameter union 🤷

🕗 Version & Regression Information

  • This changed between versions 3.8.3 and 3.9.7, and changed again between 4.2.2 and the nightly.

⏯ Playground Link

Playground link with relevant code

💻 Code

type Transform1<T> = ((value: string) => T) | (string extends T ? undefined : never);
type Transform2<T> = string extends T ? ((value: string) => T) | undefined : (value: string) => T;

function test<T>(f1: Transform1<T>, f2: Transform2<T>) {
  f1?.("hello");  // error in nightly, no error in 4.2.2
  f2?.("hello");  // error since 3.9.7, no error in 3.8.3
}

🙁 Actual behavior

Error on the call to f1 in 4.2.2, and errors on both calls in the nightly.

🙂 Expected behavior

Both calls should succeed. The function return value is ignored, so string extends T should have no impact on the validity of the expression.

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