Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

strictnullchecks - Typescript and filter Boolean

Consider following code with strictNullChecks turned on:

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);

It fails to compile due to:

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; }'.

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

Same problem with null.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

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.

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...