Reputation: 5864
I have a function that accepts x
and y
. One of the coordinates is always null
. Another one is always number
. The function returns the value of a not-null coordinate: either x
or y
. The function always returns a number.
function test({ x, y }: { x: null; y: number } | { x: number; y: null }): number {
if (x === null) {
// y should be recognized as 'number', but it is 'number | null'
return y; // ERROR
}
return x;
}
test({x: null, y: 42 }); // 42
Is it possible to keep the return type of this function always as a number
?
Upvotes: 2
Views: 1175
Reputation: 15116
Currently, TypeScript infers number | null
for both x
and y
as it won't take into account any dependencies between them that follow from the union type. You simplify the problem a bit by not destructuring the argument object, which will allow TypeScript to identify it as a discriminating union and narrow its type based on checks on x
(or y
):
function test(arg: { x: null; y: number } | { x: number; y: null }): number {
if (arg.x === null) {
return arg.y;
}
return arg.x;
}
Upvotes: 1
Reputation: 11994
If you are sure about your requirements you can try the following:
function test({ x, y }: { x: null; y: number } | { x: number; y: null }): number {
return x === null && y !== null ? y : x!;
}
!
is the so called Non-null assertion operator:
A new
!
post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact.
Upvotes: 1