Differing user-defined type guard and 'typeof' type guard behaviour when narrowing 'any'
See original GitHub issueIn the below code, using a typeof type guard and an equivalent (I thought) user-defined guard, only one error is produced.
var y: any;
// Built-in type guard
if (typeof y === "string") {
y.hello = true; // Correct error - 'hello' does not exist on type string
}
// Equivalent user-defined type guard
function f(x: any): x is string {
return typeof x === "string";
}
if (f(y)) {
y.hello = true; // No error with user-defined guard
}
Playground demo. Looks like user-defined type guards won’t narrow from any
, in any circumstances, as far as I can tell.
Issue Analytics
- State:
- Created 8 years ago
- Comments:9 (5 by maintainers)
Top Results From Across the Web
Documentation - Narrowing - TypeScript
It looks at these special checks (called type guards) and assignments, and the process of refining types to more specific types than declared...
Read more >PEP 647 – User-Defined Type Guards
User-defined type guards apply narrowing only in the positive case (the if clause).
Read more >User defined type guard function and type narrowing to more ...
$as$] tells Typescript that objects of this class have a private member, that is, that its structure is different and specific. That means...
Read more >Custom Type Guards in Typescript - DEV Community
Previously, we covered various approaches that you can take to narrowing types in Typescript. Type narrowing is the process of moving the ...
Read more >TypeScript — Make types “real”, the type guard functions
by using instanceof and typeof JavaScript operators; by creating “User-Defined Type Guards”: defining your own type assertions using Functions, ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Came up on stackoverflow : http://stackoverflow.com/a/37153565/390330 🌹
This appears to be fixed for user defined type guards, but strict equality
===
appears to still not narrowany
types:Is that intentional?