What are Type Guards in TypeScript?

Instruction: Explain the concept of Type Guards and how they are used with an example.

Context: This question tests the candidate's knowledge of Type Guards and their ability to utilize them to influence the type checking behavior of TypeScript.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

A type guard is a runtime check that TypeScript can use to narrow a value in a branch. typeof, instanceof, discriminant equality and property checks are common examples. A user-defined predicate can also declare what a successful check establishes.

function formatInput(input: string | number): string { return typeof input === "string" ?...

Related Questions