TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

instanceof Promise in ternary does not narrow Promiselike in 4.1

Open brainkim opened this issue 3 years ago • 4 comments

TypeScript Version: 4.1.0-beta

Search Terms: promise promiselike instanceof Code

declare const p: PromiseLike<number>;
const p1 = p instanceof Promise ? p : Promise.resolve(p);
const p2: Promise<number> = p1.then((v) => v + 1);

Expected behavior:

No errors.

Actual behavior: p2 errors because the expression has been determined to be promise-like. Also p1 is inferred as PromiseLike & Promise.

Playground Link: https://www.typescriptlang.org/play?ts=4.1.0-beta#code/CYUwxgNghgTiAEYD2A7AzgF3gBwFzwAUYkBbASzRABkyBrEAHhQFcSAjEGAPgG4AoZOizYAjPAC8OeGSFQUYEEgBmhYuUrwA-FPxFSFEADo4aJBABuIABTYAlP0GYcAJl1qDTVh24ScIwxgAFiAoVlbmthJc8ObwANTwIvZAA

Related Issues:

brainkim avatar Nov 20 '20 05:11 brainkim

const p2: Promise = p.then((v) => v + 1);

Did you mean to use p1 instead of p?

MartinJohns avatar Nov 20 '20 10:11 MartinJohns

Ah yeah. I was wondering why the bug is only on the new version and I couldn’t reproduce the old behavior. Fixed the typescript example so it only fails on 4.1.

brainkim avatar Nov 20 '20 15:11 brainkim

I think this cooould be an instance of #41563. It’s essentially an overload selection problem—the intersected PromiseLike and Promise is a reasonably correct representation of what we know about p1, but the problem is that we now have an intersected signature for then, which equates to overloads, and no heuristics to help us pick between them.

andrewbranch avatar Nov 24 '20 22:11 andrewbranch

:wave: Hi, I'm the Repro bot. I can help narrow down and track compiler bugs across releases! This comment reflects the current state of the repro in the issue body running against the nightly TypeScript.


Issue body code block by @brainkim

:+1: Compiled

Historical Information
Version Reproduction Outputs
4.2.2, 4.3.2, 4.4.2, 4.5.2, 4.6.2

:+1: Compiled

typescript-bot avatar Apr 13 '22 23:04 typescript-bot

It seems that this have been already fixed in 4.2.2 and issue could be closed?

rubiesonthesky avatar Jan 05 '23 09:01 rubiesonthesky

@rubiesonthesky This appears to have been fixed since 4.2.2. Thanks.

brainkim avatar Jan 05 '23 23:01 brainkim