mattpocock / ts-reset

A 'CSS reset' for TypeScript, improving types for common JavaScript API's
https://www.totaltypescript.com/ts-reset
MIT License
7.9k stars 124 forks source link

`void` should be falsy #172

Closed none23 closed 9 months ago

none23 commented 1 year ago

Inside TSReset.NonFalsy, void is not considered falsy. That leads to incorrect behavior of .filter(Boolean)

declare namespace TSReset {
  type NonFalsy<T> = T extends false | 0 | '' | null | undefined | 0n 
    ? never
    : T;
}

interface Array<T> {
  filter(predicate: BooleanConstructor, thisArg?: any): TSReset.NonFalsy<T>[];
}

const fns = [
  (x?: unknown) => 1,
  () => {},
];

const nonEmptyResults = fns.map(fn => fn()).filter(Boolean)
//               ^? const nonEmptyResults: (number | void)[]

TS Playground Example

russelldavis commented 9 months ago

It's a nice idea, but making void falsy is not safe. Functions with a void return type can still return a truthy value. See https://www.typescriptlang.org/docs/handbook/2/functions.html#return-type-void

none23 commented 9 months ago

@russelldavis Yeah, I guess that makes sense, thanks