-
Notifications
You must be signed in to change notification settings - Fork 12.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Suggestion: check narrowed type in user-defined type guards #29980
Comments
For the most part we don't expect UDTGs to be checkable at all, because that's why the author is writing them in the first place. Trivial type guards which we would be able to check may as well be inlined anyway, and more error-prone type guards wouldn't be checkable anyway. |
Not necessarily—sometimes they're written just to abstract checks so we don't have to repeat them. Such is the case with const checkIsObject = (value: unknown): value is object =>
typeof value === 'object' && object !== null; |
How about a mode for type guards that asks the compiler to figure out the type of the parameter :
The use case of this is when moving a check the compiler can accurately type to a utility function. The compiler will determine the type of the specific parameter when the return of the function is true. Most of the machinery to do this is there, I think the one extension would be if the return is an expression, take the expression and figure out the type on the true case and the false case of the expression. |
For anyone who wants to achieve this today, check out fp-ts |
First time I realized type guards were as unsafe as Something like |
Why there is no validation for typeguards (playground ) ? From my understanding this code should fail in compile time type WithA = { a?: { someMethod: (x: number) => number } }
const thingWithA: WithA = { a: undefined };
const typeGuard = (obj: unknown): obj is WithA => {
return typeof obj === 'object' && obj !== null && 'unknownProp' in obj;
} |
I think your example fits the suggestion described in #21732. |
This issue has been marked as "Too Complex" and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Search Terms
validate type check user defined guard return narrow
Suggestion
This function is invalid because the type specified in the return type (
number
) does not match the reality at runtime (string
). However, TS does not currently throw a type error.Could TypeScript type check user-defined type guards? Specifically it should check the narrowed type of
value
in the function body (after all guards) matches the explicit return type.Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: