Skip to content

Inline user defined type guard #41710

Closed
Closed

Description

Search Terms

  • inline typeguard
  • user defined guard
  • if statement

Suggestion

In the logic flow there are times when typescript might not pick up the correct expected type. In that instances we can hint to the compiler by using value as MyType. However this as keyword only applies to that single use of value.

In a logic flow if I have an if statement that throws an error if it isn't an expected type then after that I should be safely be able to use value as MyType knowing that an error would have been thrown otherwise. See example 1. This is already possible with the use of dedicated methods with type guard return types but it would be nice to do this inline.
I imagine the typing would be defined as seen in example 2.

Use Cases

If the user only has one instance of using this inline typeguard they wouldn't need to extract into a separate function to get the guarding which ultimately also emits extra code.
Also if they choose not to extract then their only aternative is to use the as keyword on every reference to value or re-cast the value by value = value as MyType which I imagine will output an actual self-assignment in javascript.

Examples

Example 1 (playground link):

const obj: Record<string, any> = {
    'key': 'value'
};

if (obj !== null && typeof obj === 'object' && !Array.isArray(obj)) {
    throw new TypeError('err...');
}

console.log(obj.key); // Error, compiler not sure if `key` is available

Example 2:

type MyType = { key: string };

const obj: Record<string, any> = {
    'key': 'value'
};

if (obj !== null && typeof obj === 'object' && !Array.isArray(obj)): obj is MyType {
    throw new TypeError('err...');
}

console.log(obj.key); // Valid, compiler knows `MyType` has a `key` attribute

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, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions