Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- justify-content
- 비교연산자
- 속성
- for
- 논리연산자
- if else
- 조건문
- flex-direction
- flex
- frontend
- 함수표현식
- 문자열
- boolean
- Methods
- ELSE
- for in
- 기초
- properties
- 타입
- javascript
- align-content
- 프론트엔드
- flex-wrap
- 반복문
- for of
- 함수선언식
- 화살표함수
- 함수
- 변수
- typeof
Archives
- Today
- Total
하얀 코딩
[TypeScript - 8] 타입 가드(Type Guard) 본문
타입 가드(Type Guard)는 타입스크립트에서 특정 타입을 확인하고
해당 타입에 대한 추가적인 동작을 수행하기 위해 사용되는 메커니즘입니다.
타입 가드를 사용하면 컴파일러가 타입을 추론하고, 해당 타입에 따라 코드를 분기할 수 있게 됩니다.
이를 통해 더욱 안정적인 코드를 작성할 수 있고, 런타임 에러를 방지할 수 있습니다.
타입 가드를 사용하는 방법은 여러 가지가 있습니다.
일반적으로 typeof, instanceof, in 연산자, 사용자 정의 타입 가드 함수 등을 사용합니다.
typeof
function logValue(value: string | number) {
if (typeof value === 'string') {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
instanceof
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
}
class Cat extends Animal {
meow() {
console.log('Meow!');
}
}
class Dog extends Animal {
bark() {
console.log('Woof!');
}
}
function playWithPet(pet: Cat | Dog) {
if (pet instanceof Cat) {
pet.meow();
} else {
pet.bark();
}
}
in
interface Circle {
kind: 'circle';
radius: number;
}
interface Square {
kind: 'square';
sideLength: number;
}
type Shape = Circle | Square;
function getArea(shape: Shape) {
if ('radius' in shape) {
return Math.PI * shape.radius ** 2;
} else {
return shape.sideLength ** 2;
}
}
'TypeScript' 카테고리의 다른 글
[TypeScript - 10] readonly (0) | 2023.06.06 |
---|---|
[TypeScript - 9] 타입 단언(Type Assertion) (0) | 2023.06.06 |
[TypeScript - 7] Union( | ) / Intersection( & ) (0) | 2023.06.06 |
[TypeScript - 6] Object types (객체 타입) - type, interface (0) | 2023.06.06 |
[TypeScript - 5] Object types (객체 타입) - enum, tuple (0) | 2023.06.06 |