The TypeScript specification states in §4.15.6 about the &&
operator:
The && operator permits the operands to be of any type and produces a result of the same type as the second operand.
In Javascript, the &&
operator returns the first operand if it is falsy, otherwise it returns the second operand (see ECMA-262 §11.11).
That means that if the left operand is falsy, &&
will return a value that matches the type of the left operand. For example,
typeof ( false && {} ) === "boolean" // true typeof ( '' && 1 ) === "string" // true typeof ( null && "hello" ) === "object" // true typeof ( NaN && true ) === "number" // true
Typescript, according to the rule quoted above, would incorrectly predict the types of the above expressions to be Object
, Number
, String
and Boolean
, respectively.
Am I missing something? Is there a good reason to make the type of an &&
expression match the type of the second operand? Shouldn't the result type behave like the ||
operator, and return the best common type of the two operands, and Any
if there is no best common type?
Long story short, there's no solution here that pleases everyone.
Consider this common idiom:
var customer = GetCustomer(...); // of type 'Customer' var address = customer && customer.address; if(address) { printAddressLabel(address); // Signature: (Address) => void } else { // Couldn't find the customer or the customer has no address on file }
It'd be pretty lame to give up and decide that 'address' is 'any' because there's no best common type between Customer and Address.
In the majority of cases where the && operator is used, either the types already match, or && is being used in a value-coalescing manner like above. In either case, returning the type of the right operand gives the user the expected type.
While the type safety is technically breaking down at this point, it's not doing so in a way that's likely to result in an error. Either you're going to test the resultant value for truthiness (in which case the type is more or less irrelevant), or you're going to use the presumptive right operand for some operation (the example above doing both).
If we look at the examples you listed and pretend the left operand is indeterminately truthy or falsy and then try to write sane code that would operate on the return value, it becomes a lot clearer - there's just not much you can do with 'false && {}' that isn't already going into an 'any' argument position or truthiness test.
Addendum
Since some people were not convinced by the above, here's a different explanation.
Let's pretend for a moment that the TypeScript type system added three new types: Truthy<T>
, Falsy<T>
, and Maybe<T>
, representing possible truthy/falsy values of type T
. The rules for these types are as follows:
Truthy<T>
behaves exactly like T
Falsy<T>
Maybe<T>
, when used as the condition in an if
block, becomes a Truthy<T>
in the body of that same if
block and a Falsy<T>
in the else
blockThis would let you do things like this:
function fn(x: Maybe<Customer>) { if(x) { console.log(x.address); // OK } else { console.log(x.phone); // Error: x is definitely falsy } console.log(x.name); // Warning: x might be falsy! }
Pretty good so far. Now we can figure out what the type rules are for the && operator.
Truthy<T> && x
should be an error - if the left side is known to be truthy, you should have just written x
Falsy<T> && x
should be an error - if the left side is known to be falsy, x
is unreachable codeMaybe<T> && x
should produce... what?We know the result of Maybe<T> && x
will be either a falsy value of type T
, or x
. It cannot produce Truthy<T>
(unless T
== the type of x
in which case this entire discussion is moot). Let's call this new type Falsy<T> XOR Maybe<U>
.
What should the rules of Falsy<T> XOR Maybe<U>
be?
T
on it. If the value is of type T
, it's falsy, and not safe for use.Maybe<U>
, since Falsy<T>
and Falsy<U>
have the same behaviorsU
, because the value still might be falsy.if
test, then it should become a Truthy<U>
in the block of that if
statementIn other words, Falsy<T> XOR Maybe<U>
is Maybe<U>
. It follows all the same rules. You don't need to complicate the type system at all here by adding this weird XOR
type, because a type that fits all the specifications you need already exists.
This is a bit like giving someone a box and saying "This is either an empty box of garbage, or a full box of recyclables". You can safely empty the contents of the box into the recycling bin.
The language specification is not maintained, and wrong in this case. The result type of the &&
operator is the union of the type of the right-hand side and the falsy values of the left hand side.
From the TypeScript 2.0 release notes:
// Compiled with --strictNullChecks declare function f(x: number): string; let x: number | null | undefined; // .. let b = x && f(x); // Type of b is string | 0 | null | undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With