TypeScript/타입스크립트 TypeScript

[타입스크립트 공홈] User-Defined Type Guards

Rainbow🌈Coder 2022. 4. 26. 08:31
728x90

TypeScript: Documentation - Advanced Types (typescriptlang.org)

 

Documentation - Advanced Types

Advanced concepts around types in TypeScript

www.typescriptlang.org

User-Defined Type Guards

It would be much better if once we performed the check, we could know the type of pet within each branch.

It just so happens that TypeScript has something called a type guard. A type guard is some expression that performs a runtime check that guarantees the type in some scope.

Using type predicates

To define a type guard, we simply need to define a function whose return type is a type predicate:

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

pet is Fish is our type predicate in this example. A predicate takes the form parameterName is Type, where parameterName must be the name of a parameter from the current function signature.

Any time isFish is called with some variable, TypeScript will narrow that variable to that specific type if the original type is compatible.

// Both calls to 'swim' and 'fly' are now okay.
let pet = getSmallPet();
 
if (isFish(pet)) {
  pet.swim();
} else {
  pet.fly();
}
728x90