Sobes.tech
Middle

What is a Type Guard in TypeScript?

sobes.tech AI

Answer from AI

Type Guard in TypeScript is a special function or expression that allows narrowing the type of a variable within a conditional code block. Type Guard helps the compiler understand that a variable has a more specific type in a certain part of the code than initially declared.

For example, a function with a return value param is SomeType is a user-defined Type Guard:

function isString(value: unknown): value is string {
  return typeof value === 'string';
}

function example(value: unknown) {
  if (isString(value)) {
    // Here, TypeScript knows that value is a string
    console.log(value.toUpperCase());
  } else {
    // Here, value is not a string
  }
}

Type Guards are useful for safely working with variables whose types may be a union of multiple types. They enhance safety and development convenience by preventing type errors at runtime.

What is a Type Guard in TypeScript? — Frontend - sobes.tech