Type Guards

Type guards allow you to narrow down the type of an object within a certain scope. This can be done using typeof, instanceof, or even user-defined type guards.

if (typeof someVariable === 'string') {
    // In this block, someVariable is treated as a string


Define a function that takes a union type of number or string as an argument. If it's a number, return its square. If it's a string, return its length.

Copyright © learn-ts.org. Read our Terms of Use and Privacy Policy