Sobes.tech
Junior — Middle

Can you explain what type guard (Type Guard) is and how it is used in TypeScript?

sobes.tech AI

Answer from AI

Type Guard in TypeScript is a way to refine the type of a variable at runtime so that the compiler can work with it safely. Type Guard helps avoid errors related to incorrect type usage.

For example, if you have a variable that can be either a string or a number, you can use a Type Guard to check its type and perform appropriate actions:

function example(value: string | number) {
  if (typeof value === 'string') {
    // Here, TypeScript knows that value is a string
    console.log(value.toUpperCase());
  } else {
    // Here, value is a number
    console.log(value.toFixed(2));
  }
}

Type Guard can be implemented using typeof, instanceof, or custom functions that perform type checks.

Can you explain what type guard (Type Guard) is and… - sobes.tech