Closed as not planned
Description
Search Terms
validate type check user defined guard return narrow
Suggestion
const checkIsNumber = (value: unknown): value is number => typeof value === "string";
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.
const checkIsNumber = (value: unknown): value is number =>
typeof value === "string" &&
(() => {
// TS knows here that the type is narrowed to `string`.
// This does not match the explicit return type of this user-defined type guard (`number`).
// Therefore, TS could/should error?
value;
return typeof value === "string";
})();
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.