oz1cz oz1cz - 3 months ago 15
TypeScript Question

Typescript conversion to boolean

In Typescript I can do this:

var xxx : some_type;

if (xxx)
foo();
else
bar();


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
foo(xxx)
and have xxx treated as a boolean, regardless of its type. But Typescript won't allow that.

I tried this:

foo(<boolean>xxx);


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

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

foo(!!xxx);

Alternatively, cast it to any

foo(<any>xxx);