typescript 打字稿转换为布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20093613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:09:53  来源:igfitidea点击:

Typescript conversion to boolean

typescript

提问by oz1cz

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.

这里 xxx 将被视为布尔值,无论其类型如何。

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.

我希望能够调用foo(xxx)并将 xxx 视为布尔值,无论其类型如何。但是 Typescript 不允许这样做。

I tried this:

我试过这个:

foo(<boolean>xxx);

but that Typescript won't allow that either.

但 Typescript 也不允许这样做。

I can do this:

我可以做这个:

foo(xxx ? true : false);

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

但这似乎有点傻。有没有更好的方法来做到这一点?

回答by Kna?is

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

您可以使用 Typescript 允许并且在 JavaScript 中运行良好的技巧:

foo(!!xxx);

Alternatively, cast it to any

或者,将其转换为 any

foo(<any>xxx);

回答by dug

While you can't cast a number directly to a boolean, you can cast it to the wrapper Boolean class and immediately unwrap it. For example:

虽然您不能将数字直接转换为布尔值,但您可以将其转换为包装 Boolean 类并立即解开它。例如:

foo(<boolean><Boolean>xxx);

While clumsy, it avoids the type erasure of casting to <any>. It's also arguably less obscure & more readable than the !!approach (certainly so in the transpiled js code).

虽然笨拙,但它避免了强制转换为<any>. 与这种!!方法相比,它也可以说不那么晦涩且更具可读性(在转译的 js 代码中当然如此)。

回答by benlambert

With TypeScript 2.0.2 you can do this:

使用 TypeScript 2.0.2 你可以这样做:

type Falsey = '' | 0 | false | null | undefined;

function eatFruit(fruit: string | Falsey) { 
  if (fruit) {
    alert(`Ate ${fruit}`);
  } else {
    alert('No fruit to eat!');
  }
}

const fruits = ['apple', 'banana', 'pear'];
eatFruit(fruits[0]); // alerts 'Ate apple'
eatFruit(fruits[1]); // alerts 'Ate banana'
eatFruit(fruits[2]); // alerts 'Ate pear'
eatFruit(fruits[3]); // alerts 'No fruit to eat!'

const bestBeforeDay = 12;
let day = 11;
eatFruit(day < bestBeforeDay && 'peach'); // alerts 'Ate peach'
day += 1;
eatFruit(day < bestBeforeDay && 'peach'); // alerts 'No fruit to eat!'

let numMangos = 1;
eatFruit(numMangos && 'mango'); // alerts 'Ate Mango'
numMangos -= 1;
eatFruit(numMangos && 'mango'); // alerts 'No fruit to eat!'

回答by Craft Master

foo(!!xxx); // This is the common way of coercing variable to booleans.
// Or less pretty
foo(xxx && true); // Same as foo(xxx || false)

However, you will probably end up duplicating the double bang everytime you invoke fooin your code, so a better solution is to move the coerce to boolean inside the function DRY

但是,每次foo在代码中调用时,您可能最终都会复制双爆炸,因此更好的解决方案是将强制转换为函数DRY内的布尔值

foo(xxx);

foo(b: any){
  const _b = !!b;
  // Do foo with _b ...
}
  /*** OR ***/
foo(b: any){
  if(b){
    // Do foo ...
  }
}

回答by Abdus Salam Azad

Use this

用这个

YourMethod(!!isEnabled);

'!!' is used for type casting to boolean

'!!' 用于类型转换为布尔值

回答by asusfan

Here's a simple function that will handle most scenarios, including handling booleans as an input (just in case):

这是一个可以处理大多数情况的简单函数,包括将布尔值作为输入处理(以防万一):

type Falsey = undefined | null;
const parseBoolean = (val: string | boolean | number | Falsey): boolean => {
  const s = val && val.toString().toLowerCase().trim();
  if (s == 'true' || s == '1')
    return true;
  return false; 
}

And here's a jest test to go with it:

这是一个与之配套的玩笑测试:

describe('Boolean Parser', () => {
    [
        { val: 'true', expected: true },
        { val: 'false', expected: false },
        { val: 'True', expected: true },
        { val: 'False', expected: false },
        { val: 'TRUE', expected: true },
        { val: 'FALSE', expected: false },
        { val: '', expected: false },
        { val: '1', expected: true },
        { val: '0', expected: false },
        { val: false, expected: false },
        { val: true, expected: true },
        { val: undefined, expected: false },
        { val: null, expected: false },
        { val: 0, expected: false },
        { val: 1, expected: true },
        { val: 111, expected: false }
    ].forEach(args => {
        it(`should parse ${args.val} to boolean`, () => {
            expect(parseBoolean(args.val)).toBe(args.expected);
        });
    })
});

回答by Lubo

if(xxx) {...} //read as TRUE if xxx is NOT undefined or null if(!xxx) {...} //read as TRUE if xxx IS undefined or null

if(xxx) {...} //如果 xxx 未定义或为空,则读为 TRUE if(!xxx) {...} //如果 xxx 未定义或为空,则读为 TRUE

For a string like 'true' or 'false': xxx.toLowerCase().trim() === 'true' ? true : false

对于像 'true' 或 'false' 这样的字符串: xxx.toLowerCase().trim() === 'true' ? 真假

so:

所以:

var zzz = 'true'; //string
var yyy = [];  //array

...

...

if(zzz.toLowerCase().trim() === 'true') { ... }  // quick string conversion

...

...

if(yyy ? true : false) { ... }  // quick any conversion - it's TRUE if it's not null or undefined

...

...

// in a catch-all function

if(toBoolean(zzz)) { ... }
if(toBoolean(yyy)) { ... }


toBoolean(xxx: any): boolean {
  if(xxx) {
    const xStr = xxx.toString().toLowerCase().trim();
    if(xStr === 'true' || x === 'false') {
      return xStr === 'true' ? true : false;
    } else {
      return xxx ? true : false;
    }
  } else {
    return false;
  }
}