Skip to content

Incorrect type inference on union type, unless using a third property as a discriminantΒ #57758

Closed as not planned
@FrenchDilettante

Description

@FrenchDilettante

πŸ”Ž Search Terms

"inference" "inference narrow" "inference discriminant" "inference union"

πŸ•— Version & Regression Information

Tested on multiple versions, this is not a new bug.

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.4.2#code/C4TwDgpgBA6gTgewHYHMCSSBmE4SQY2gF4oBvAKAEgBbAVwBtgBLMeiALimDlogG4qANwCG9XpwDO3JqgDaAXQGV8o+gCNh+ANacAFAH1J0ufICUUIgD4oghEwAmAgL5QAPmSp1GLNp0yiJfiFRcSgpOBkUJRV6dU0dKAMjCNRzKxs7R3InAXJMWgJmZCg2YABVCQxsOF1hTnhkdCwcPEJzCkphADoYuO1arpExCFMlJkxE7q9mVhGPSk6e1Q1+7qHeUaoXCHpA+cXela0B9ZGlJ2zyIA

πŸ’» Code

type Selection = {
	multiple: true;
	value: string[];
	callback: (_: string[]) => void;
} | {
	multiple: false;
	value: string;
	callback: (_: string) => void;
};

function test(a: Selection) {
	// Error: Typescript does not recognise that `value` and `callback` use the same type.
	a.callback(a.value);
	if (a.multiple) {
		// Valid: Typescript narrowed down the type to `string[]`
		a.callback(a.value);
	} else {
		// Valid: Typescript narrowed down the type to `string`
		a.callback(a.value);
	}
}

πŸ™ Actual behavior

Typescript does not recognise that callback will always accept value as a parameter, since they both use either string or string[].

Interestingly, Typescript can infer the types properly using the if (multiple) { ... } condition.

πŸ™‚ Expected behavior

All three callback(value) calls should be valid, from a type point of view.

Additional information about the issue

No response

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