Skip to content

Inferred type in generic function is too specific with strictNullChecks #18734

@e98cuenc

Description

@e98cuenc

TypeScript Version: 2.5.2

Code

function ifnull<T>(x: T | null | undefined, def: T): T
{
	return x != null ? x : def;
}

ifnull(2, 1);

Expected behavior:

The inferred type for T should not depend on strictNullChecks.

Actual behavior:

It is number when used without strictNullChecks, but it is the type 1 when used with strictNullChecks.

I understand you don't want to infer the intersection type 1 | 2, but I think it will be more useful to infer the type number. Many generic functions accept two arguments of the same type (two numbers, two strings, etc.), but when you call it with different values Typescript (with strictNullChecks) will always issue an error because it will infer the incompatible types value1 and value2 for T.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions