-
Notifications
You must be signed in to change notification settings - Fork 13k
Description
Suggestion
π Search Terms
- assert
- type guard
- object property
- dynamic
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
TypeScript recently introduced assertion type guards, like follows:
function assertIsDefined<T>(value: T | undefined ): asserts value is T {
if (value === undefined) {
throw new AssertionError({ message: `Expected value not to be undefined` });
}
}
assertIsDefined(value);
This is great, but what I would love is for the error message to log the variable name. The first thing I did was change the function to accept an object:
function assertIsDefined<T>(obj: { value: T | undefined }): asserts obj is { value: T } {
const [key, value] = Object.entries(obj)[0];
if (value === undefined) {
throw new AssertionError({ message: `Expected "${key}" not to be undefined` });
}
}
assertIsDefined({ value });
However this doesn't work. The compiler sees value
, and the value within { value }
as separate variables.
I would love to take it further, and have multiple assertion checks in one, like:
assertIsDefined({ value1, value2 });
The type guard could look like:
export function assertIsDefined<T>(obj: { [value: string]: T | undefined }): asserts obj is { [value: string]: T } {
for (const [key, value] of Object.entries(obj)) {
if (value === undefined) {
throw new AssertionError({ message: `Expected "${key}" not to be undefined` });
}
}
}
π Motivating Example
Assertion type guards to work for object properties.
π» Use Cases
The type guard currently only works for values like value
, but does not recognise that the check on { value }
should work. Supporting this would enable dynamic assertion checks, supporting multiple input values as shown from the Suggestions section above.