elierotenberg / elierotenberg/typed-assert

More useful assertions?

Open
#14 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
TypeScript
Stars
53
Forks
3
PR merge metrics
No merged PRs in 30d

Description

I wonder why the set of assertions is somewhat scanty.

For example, it seems pretty common to assert for non-empty properties of an object. It may look like this:

```ts
// Say, `options` is { foo?: string, bar?: number, baz?: boolean }
assertPropsNotEmpty(options, ['foo', 'bar', 'baz'], (items) => `Options requires properties: "${items.join(', ')}"`);
// Now `options` is { foo: string, bar: number, baz: boolean }
```

This is especially relevant now when GRPC with Protobuf is everywhere, and the last guy doesn't seem to support "required" object props, so everything is optional (which does not always make sense from the business perspective).

My current implementation:

```ts
export function assertPropsNotEmpty(
value: T,
props: K[],
message: string | ((badProps: K[]) => string),
): asserts value is T & { [Key in K]-?: NonNullable } {
const emptyProps = props.filter((prop) => value[prop] == null);
if (value == null || emptyProps.length > 0) {
throw new AssertError(
typeof message === 'string'
? `Not-empty props assertion "${message}" failed for props: "${emptyProps.join(', ')}"`
: message(emptyProps),
);
}
}
```

I have more or those.

I would prefer to move to a solid library (like `typed-assert`), instead of copy-pasting these things from project to project :)

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.