Skip to content

undefined type from optional chaining doesn't produce correct generic inference candidate from union #34579

Closed
@RyanCavanaugh

Description

@RyanCavanaugh

TypeScript Version: 10/18/2019 nightly

Search Terms: optional chaining generic inference undefined

Code

declare function unbox<T>(box: { value: T | undefined }): T;
declare const su: string | undefined;

const b1 = { value: su?.length };
// Incorrect error - T inferred to be number | undefined
const v1: number = unbox(b1);

// No error
const b2 = { value: su?.length as number | undefined };
const v2: number = unbox(b2);

// No error
const b3: { value: number | undefined } = { value: su?.length  };
const v3: number = unbox(b3);

Expected behavior: In all cases, T should be inferred to be number

Actual behavior: When the undefined part of the union of the type of value originates in an optional chaining, it doesn't infer correctly

Playground Link: http://www.typescriptlang.org/play/?ts=Nightly&ssl=1&ssc=1&pln=15&pc=1#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXzQCMcAPAHgBUA+ACmJIC54BveANygmRCYvgB8CqUIiyoQweAF8AlLwDcAWABQoSLARg8AZwzxtyJrphiA5gKEixEpcpVbUu+IQCM8ALwt2nbkeQB+ADoIEFRTDAALaVsAehj4AEl0HBg4THgQVJT4AFp4PjFETLhJDBxnBFRkAFtCTIs0K3Fgex09NhcmKtr6zyJSOhcZWxU4+AA5cuKU1sc9QgAmDy8OLh59AODQ8KiobXhuupgG4RBRZujZpzYFrpqj5f6SOgXhlVH4yYysmCv5gGYmKxVr4Dvd6oJGmdrJIpMtgT51gYgiEwpF4JdlA5roCwT1jn1UPQ6P83sogA (nightly link)

Related Issues: Nope

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions