Chuyển đổi Typescript sang boolean
Trong Typescript tôi có thể làm điều này:
var xxx : some_type;
if (xxx)
foo();
else
bar();
Ở đây xxx sẽ được xử lý như một giá trị boolean, bất kể loại của nó là gì.
Tôi muốn làm cùng một việc trong một đối số hàm. Tôi có hàm này:
function foo(b : boolean) { ... }
Tôi muốn có thể gọi foo(xxx) và để xxx được xử lý như một giá trị boolean, bất kể loại của nó là gì. Nhưng Typescript sẽ không cho phép điều đó.
Tôi đã thử cái này:
foo(<boolean>xxx);
nhưng Typescript cũng sẽ không cho phép điều đó.
Tôi có thể làm việc này:
foo(xxx ? true : false);
Nhưng điều đó có vẻ hơi ngớ ngẩn. Có cách nào tốt hơn để làm không?
Câu trả lời #1
Bạn có thể sử dụng mẹo dấu chấm than kép mà Typescript cho phép và hoạt động tốt trong JavaScript:
foo(!!xxx);
Ngoài ra, ép kiểu nó thành any
foo(<any>xxx);
foo(xxx as any);
Câu trả lời #2
Đây là giải pháp của tôi cho "typescript": "^3.3.3":
function toBool(a: any) {
return Boolean(a).valueOf();
}
export { toBool };
kiểm thử đơn vị:
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();
});
});
});
kết quả kiểm thử đơn vị:
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
Câu trả lời số 3
Cách rõ ràng nhất để làm điều này với TypeScript là sử dụng một constructor Boolean:
Boolean(someVal);
trong trường hợp của bạn sẽ là:
foo(Boolean(xxx));
xin lưu ý rằng hàm khởi tạo được sử dụng mà không có từ khóa "new". Bởi vì nếu bạn thêm nó, bạn sẽ tạo ra một đối tượng boolean mới thay vì ép kiểu giá trị:
Boolean(false) == false
nhưng
new Boolean(false) == true
bởi vì nó là một đối tượng
