GeezerVison is showing github.com — Function parameter type inference error · Issue #59949 · microsoft/TypeScript
Function parameter type inference error #59949ActivityMartinJohns commented on Sep 12, 2024 Because checking what value type is does not have any relevance for what type the value of extend is.
This is a perfectly valid call: func<Type.A | Type.B>(Type.A, 1); lengyuxuan commented on Sep 12, 2024
Because checking what value type is does not have any relevance for what type the value of extend is.
This is a perfectly valid call: func<Type.A | Type.B>(Type.A, 1);
How should I constrain the type of "extend" ? Do you have any suggestions ? Thank you so much ! jcalz commented on Sep 12, 2024 Duplicate #33014
For now, if you need this behavior you either need to rewrite in terms of #47109 and use generic indexing instead of control flow anlaysis:
function func<T extends Type>(type: T, extend: X<T>) {
const x: { [K in Type]: (type: K, x: X<K>) => void } = {
[Type.A](type, extend) {
console.log(type, extend);
// ^? (parameter) extend: string
},
[Type.B](type, extend) {
}
}
x[type](type, extend);
}
func(Type.A, '');
func(Type.B, 1);
func(Math.random() < 0.99 ? Type.A : Type.B, 1); // still allowed, #47109 technically unsound this way
or, you need to use control flow analysis on a discriminated union and not use generics:
function func(...[type, extend]: { [T in Type]: [type: T, extend: X<T>] }[Type]) {
if (type === Type.A) {
console.log(type, extend);
// ^? (parameter) extend: string
}
}
func(Type.A, '');
func(Type.B, 1);
func(Math.random() < 0.99 ? Type.A : Type.B, 1); // error
Playground link to code Reacted by Ryan Cavanaugh and fangjin lengyuxuan commented on Sep 13, 2024
Duplicate #33014
For now, if you need this behavior you either need to rewrite in terms of #47109 and use generic indexing instead of control flow anlaysis:
function func<T extends Type>(type: T, extend: X<T>) {
const x: { [K in Type]: (type: K, x: X<K>) => void } = {
[Type.A](type, extend) {
console.log(type, extend);
// ^? (parameter) extend: string
},
[Type.B](type, extend) {
}
}
x[type](type, extend);
}
func(Type.A, '');
func(Type.B, 1);
func(Math.random() < 0.99 ? Type.A : Type.B, 1); // still allowed, #47109 technically unsound this way
or, you need to use control flow analysis on a discriminated union and not use generics:
function func(...[type, extend]: { [T in Type]: [type: T, extend: X<T>] }[Type]) {
if (type === Type.A) {
console.log(type, extend);
// ^? (parameter) extend: string
}
}
func(Type.A, '');
func(Type.B, 1);
func(Math.random() < 0.99 ? Type.A : Type.B, 1); // error
Playground link to code
Good job locked as resolved and limited conversation to collaborators on Oct 22, 2025
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|