Skip to content

Assert value type guard for dynamic object propertiesΒ #46184

@cristianrgreco

Description

@cristianrgreco

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions