개발일지
[TS] 10. 타입스크립트의 핵심 #1 - Type과 Interface 본문
22.09.19 월
Type Alias와 Interface:
Type vs Interface (기술 측면)
type PositionType = {
x: number;
y: number;
};
interface PositionInterface {
x: number;
y: number;
}
1. object (type) : 둘 다 가능
// object ★
const obj1: PositionType = {
x: 1,
y: 1,
};
const obj2: PositionInterface = {
x: 1,
y: 1,
z: 1,
};
2. class (implements) : 둘 다 가능
// class ★
class Pos1 implements PositionType {
x: number;
y: number;
}
class Pos2 implements PositionInterface {
x: number;
y: number;
}
3. extends : 둘 다 가능
interface ZPositionInterface extends PositionInterface {
z: number;
}
type ZPositionType = PositionType & { z: number };
4. merge : interface만 가능
interface PositionInterface {
z: number;
}
// 위의 PositionInterface와 merge되어 x,y,z를 갖게 됨
type PositionType { //type은 중복 불가
}
5. computed properties : type만 가능
type Person = {
name: string;
age: number;
};
type Name = Person['name']; // string 타입
type NumberType = number;
type Direction = 'left' | 'right';
Type vs Interface (개념 측면)
- interface
- 규약 정의할 때 사용
- type
- 데이터에 대한 type 나타내고 싶을 때 사용
// 예시)
type Position = {
x: number;
y: number;
};
const pos: Position = { x: 0, y: 0 };
'JS, TS > [TS | 강의] TS·OOP' 카테고리의 다른 글
[TS] 10. 타입스크립트의핵심 #3 - Utility Types (0) | 2022.11.09 |
---|---|
[TS] 10. 타입스크립트의핵심 #2 - index, mapped, conditional type (0) | 2022.11.09 |
[TS] 9. 에러 처리 하기 (0) | 2022.11.08 |
[TS] 7. 제네릭-Quiz (0) | 2022.10.30 |
[TS] 6. 제네릭 (0) | 2022.10.30 |