When placing a type guard for arg1 I'd expect arg2 to be inferred automatically, but it doesn't.
Anyone an idea why this isn't working? what's the best alternative? Thanks so much!
You can see the types in action here. Simply hover over arg2 to see the inferred type.
function example<T extends 'foo' | 'bar'>(
arg1: T,
arg2: T extends 'foo' ? string : number
) {
if (arg1 === 'foo') {
arg2 // should be string?
}
if (arg1 === 'bar') {
arg2 // should be number?
}
}
However, invoking the function does correctly apply the second arg type:
Here's another example using a typed object based on generics:
type Test <T extends boolean> = {
multiple: T;
value: T extends true ? string : number;
};
// this doesn't work?
function test <T extends boolean>(a: Test<T>) {
if (a.multiple) {
a.value // string | number?
}else{
a.value // string | number?
}
}
// this works!
function test2 (a: Test<true> | Test<false>) {
if (a.multiple) {
a.value // is string
}else{
a.value // is number
}
}
See playground

