- Published on
타입 가드(활용 예시 포함)
- Authors
- Name
- sulmo
런타임 시점에 특정 값이 특정 타입임을 확인하는 함수이다.
보통 함수를 정의하거나 변수를 정의할 때, 타입을 할당 하면서 범위를 좁히는 행위들이 있으며, 조건문을 통해 typeof나 instanceof 와 같은 문법으로도 가드할 수 있다.
몇몇 커스텀 가드 함수들을 통해 타입 가드를 진행하기도 한다.
나열해 보자면,
typeof
를 사용한 타입 가드
1. function isString(value: any): value is string {
return typeof value === 'string'
}
const example: any = 'hello'
if (isString(example)) {
// 여기서 example은 string 타입으로 추론됩니다.
}
instanceof
를 사용한 타입 가드
2. class Dog {
bark() {
console.log('Woof!')
}
}
class Cat {
meow() {
console.log('Meow!')
}
}
function isDog(animal: any): animal is Dog {
return animal instanceof Dog
}
const pet: Dog | Cat = new Dog()
if (isDog(pet)) {
// 여기서 pet은 Dog 타입으로 추론됩니다.
pet.bark()
} else {
pet.meow()
}
3. 커스텀 타입 가드 함수
interface Fish {
swim: () => void
}
interface Bird {
fly: () => void
}
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined
}
const pet: Fish | Bird = { swim: () => console.log('swimming') }
if (isFish(pet)) {
// 여기서 pet은 Fish 타입으로 추론됩니다.
pet.swim()
} else {
pet.fly()
}
커스텀은 정의할 때, 시경 많이 써야할 듯.
in
연산자를 사용한 타입 가드
4. interface Fish {
swim: () => void
}
interface Bird {
fly: () => void
}
function isFish(pet: Fish | Bird): pet is Fish {
return 'swim' in pet
}
const pet: Fish | Bird = { swim: () => console.log('swimming') }
if (isFish(pet)) {
// 여기서 pet은 Fish 타입으로 추론됩니다.
pet.swim()
} else {
pet.fly()
}
5. 유니언 타입의 속성을 이용한 타입 가드
type Square = { kind: 'square'; size: number }
type Rectangle = { kind: 'rectangle'; width: number; height: number }
type Shape = Square | Rectangle
function area(shape: Shape): number {
if (shape.kind === 'square') {
return shape.size * shape.size
} else {
return shape.width * shape.height
}
}
const shape: Shape = { kind: 'square', size: 10 }
console.log(area(shape)) // 100
4, 5번의 활용이 많이 필요했었는데 사용하지 못했던 개념 같습니다. [PublicDashboard, <->
PrivateDashboard] [GeneralAccount <->
TrustedAccount] 등등