Skip to content

Inconsistent type inference for cases of one and multiple values #32349

Closed
@MJ-Max

Description

@MJ-Max

To me it looks like tsc is able to infer the correct type in the first case as it tries hard to find a type that matches both possible return values. In the other two cases which return only one string it doesn't search and assumes the return value is a plain string, even though the intended type of the return value should indicate it is not.

Search Terms: Type Promise is not assignable to type promise inconsistent

Code

type DooDad = 'SOMETHING' | 'ELSE' ;

class Interesting {

	public compiles = () : Promise<DooDad> => {
		return Promise.resolve().then(() => {
			if (1 < 2) {
				return 'SOMETHING';
			}
			return 'ELSE';
		});
	};

	public doesnt = () : Promise<DooDad> => {
		// TS2322: Type Promise<string> is not assignable to type Promise<DooDad>
		// Type 'string' is not assignable to type 'DooDad'
		return Promise.resolve().then(() => {
		//return Promise.resolve().then(() : DooDad => { // specifying return type here fixes the issue
			return 'ELSE';
		});
	};

	public slightlyDifferentErrorMessage = () : Promise<DooDad> => {
		// TS2322: Type Promise<string> is not assignable to type Promise<DooDad>
		return Promise.resolve().then(() => {
		//return Promise.resolve().then(() : DooDad => { // specifying return type here fixes the issue
			if (1 < 2) {
				return 'SOMETHING';
			}
			return 'SOMETHING';
		});
	};

}

Expected behavior: All three functions compile and DooDad is inferred in all three cases ( alternatively, it is inferred in no case; this inconsistency is the worst case scenario IMO )

Actual behavior: First function compiles, the other two fail with TS2322

Playground Link: here

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions