oz1cz oz1cz - 1 year ago 307
TypeScript Question

Typescript conversion to boolean

In Typescript I can do this:

var xxx : some_type;

if (xxx)

Here xxx will be treated as a boolean, regardless of its type.

I would like to do the same thing in a function argument. I have this function:

function foo(b : boolean) { ... }

I want to be able to call
and have xxx treated as a boolean, regardless of its type. But Typescript won't allow that.

I tried this:


but that Typescript won't allow that either.

I can do this:

foo(xxx ? true : false);

But that seems a bit silly. Is there a better way to do it?

Answer Source

You can use this trick which Typescript does allow and which works fine in JavaScript:


Alternatively, cast it to any

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download