Typescript转换为boolean

oz1*_*1cz 51 typescript

在Typescript中我可以这样做:

var xxx : some_type;

if (xxx)
    foo();
else
    bar();
Run Code Online (Sandbox Code Playgroud)

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

我想在函数参数中做同样的事情.我有这个功能:

function foo(b : boolean) { ... }
Run Code Online (Sandbox Code Playgroud)

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

我试过这个:

foo(<boolean>xxx);
Run Code Online (Sandbox Code Playgroud)

但是那个Typescript也不允许这样做.

我可以做这个:

foo(xxx ? true : false);
Run Code Online (Sandbox Code Playgroud)

但这似乎有点傻.有没有更好的方法呢?

Kna*_*ģis 73

你可以使用这个技巧,这个技巧是Typescript允许的,并且可以在JavaScript中正常工作:

foo(!!xxx);
Run Code Online (Sandbox Code Playgroud)

或者,把它投到 any

foo(<any>xxx);
Run Code Online (Sandbox Code Playgroud)

  • 字符串'false'是JavaScript中的"truthy"(https://developer.mozilla.org/en-US/docs/Glossary/Truthy),因此它可以正常工作. (13认同)
  • @Toolkit,在javascript中,通过扩展名Typescript,如果字符串是空字符串(或未定义),则该字符串仅为false. (6认同)
  • 这不起作用:console.log("!!'false':",!!'false')给了我!!'false':true (5认同)
  • @Roxy'Pro `!!xxx` 字面意思是“not not xxx”,所以它是一个双重否定,有效地将表达式“xxx”转换为布尔值。 (2认同)

fs_*_*_dm 10

使用打字稿执行此操作的最明显方法是使用布尔构造函数:

Boolean(someVal);
Run Code Online (Sandbox Code Playgroud)

在你的情况下它将是:

foo(Boolean(xxx));
Run Code Online (Sandbox Code Playgroud)

请注意,使用构造函数时不带“new”关键字。因为如果添加它,您将创建一个新的布尔对象,而不是转换该值:

Boolean(false) == false 
Run Code Online (Sandbox Code Playgroud)

new Boolean(false) == true
Run Code Online (Sandbox Code Playgroud)

因为它是一个对象


dug*_*dug 8

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

foo(<boolean><Boolean>xxx);
Run Code Online (Sandbox Code Playgroud)

虽然笨拙,但它避免了铸造的类型擦除<any>.它也可以说比!!方法更简洁,更易读(在转换的js代码中也是如此).

  • 双重渲染似乎很长,写入和垃圾阅读,而"!!"只是真正初级javascript开发人员的模糊. (3认同)

sli*_*wp2 8

这是我的解决方案"typescript": "^3.3.3"

function toBool(a: any) {
  return Boolean(a).valueOf();
}

export { toBool };
Run Code Online (Sandbox Code Playgroud)

单元测试:

import { toBool } from '../../utils/bool';

describe('bool', () => {
  describe('#toBool', () => {
    it('should convert string to boolean', () => {
      expect(toBool('false')).toBeTruthy();
      expect(toBool('')).toBeFalsy();
    });
    it('should convert number to boolean', () => {
      expect(toBool(1)).toBeTruthy();
      expect(toBool(0)).toBeFalsy();
      expect(toBool(-1)).toBeTruthy();
      expect(toBool(Infinity)).toBeTruthy();
      expect(toBool(-Infinity)).toBeTruthy();
    });
    it('should convert null to boolean', () => {
      expect(toBool(null)).toBeFalsy();
    });
    it('should convert undefined to boolean', () => {
      expect(toBool(undefined)).toBeFalsy();
    });
    it('should convert NaN to boolean', () => {
      expect(toBool(NaN)).toBeFalsy();
    });
    it('should convert object to boolean', () => {
      expect(toBool({})).toBeTruthy();
    });
    it('should convert array to boolean', () => {
      expect(toBool([])).toBeTruthy();
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

单元测试结果:

 PASS  src/__tests__/utils/bool.spec.ts
  bool
    #toBool
      ? should convert string to boolean (3ms)
      ? should convert number to boolean (1ms)
      ? should convert null to boolean (1ms)
      ? should convert undefined to boolean
      ? should convert NaN to boolean (1ms)
      ? should convert object to boolean (1ms)
      ? should convert array to boolean

Test Suites: 1 passed, 1 total
Tests:       7 passed, 7 total
Snapshots:   0 total
Time:        3.79s, estimated 4s
Run Code Online (Sandbox Code Playgroud)


ben*_*ert 7

使用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!'
Run Code Online (Sandbox Code Playgroud)


Abd*_*zad 5

用这个

YourMethod(!!isEnabled);
Run Code Online (Sandbox Code Playgroud)

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