打字稿和过滤布尔值 [英] Typescript and filter Boolean

查看:14
本文介绍了打字稿和过滤布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑遵循 代码strictNullChecks 打开:

var a: (number | null)[] = [0, 1, 2, 3, null, 4, 5, 6];
var b: { value: number; }[] = a.map(x => x != null && { value: x }).filter(Boolean);

编译失败的原因:

Type '(false | { value: number; })[]' is not assignable to type '{ value: number; }[]'.
  Type 'false | { value: number; }' is not assignable to type '{ value: number; }'.
    Type 'false' is not assignable to type '{ value: number; }'.

但是很明显,false 会被 .filter(Boolean) 过滤掉.

But it is absolutely clear, that false will be filtered away by .filter(Boolean).

null 也有同样的问题.

有没有办法(除了写as number[])来标记那个值不包含falsenull?>

Is there a way (except writing as number[]) to mark that value doesn't contain false or null?

推荐答案

如果你真的不想改变生成的 JavaScript,而是更喜欢强制 TypeScript 编译器识别 Boolean 是为了防止 false 值,您可以这样做:

If you really don't want to change the generated JavaScript, and instead prefer to force the TypeScript compiler to recognize that Boolean is serving as a guard against false values, you can do this:

type ExcludesFalse = <T>(x: T | false) => x is T;     
var b: { value: number; }[] = a
  .map(x => x != null && { value: x })
  .filter(Boolean as any as ExcludesFalse);

这是有效的,因为您断言 Boolean类型保护,并且因为 Array.filter()重载,如果回调是类型保护,则返回一个缩小的数组.

This works because you are asserting that Boolean is a type guard, and because Array.filter() is overloaded to return a narrowed array if the callback is a type guard.

以上(Boolean as any as ExcludesFalse)是我能想出的最干净的代码,它既有效又不会改变生成的 JavaScript.常量Boolean 被声明为全局BooleanConstructor 接口的一个实例,你可以将一个ExcludesFalse 类的类型保护签名合并到BooleanConstructor,但不能让您只说 .filter(Boolean) 并让它工作.您可以通过类型保护变得更有趣,并尝试表示对所有虚假值的保护(除了 NaN) 但您的示例不需要它.

The above (Boolean as any as ExcludesFalse) is the cleanest code I could come up with that both works and doesn't change the generated JavaScript. The constant Boolean is declared to be an instance of the global BooleanConstructor interface, and you can merge an ExcludesFalse-like type guard signature into BooleanConstructor, but not in a way that allows you to just say .filter(Boolean) and have it work. You can get fancier with the type guard and try to represent guarding against all falsy values (except NaN) but you don't need that for your example.

无论如何,希望有所帮助;祝你好运!

Anyway, hope that helps; good luck!

这篇关于打字稿和过滤布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆