type alias
타입을 변수에 담을 수 있다. type alias는 영문 대문자로 시작하는 규칙이 있다.
type Name = string | number;
let 이름 :Name = 'kim';
type MyObject = {
name? : string,
age : number
}
let 철수 :MyObject = {
name : 'kim',
age : 50
}
Object 변경 에러띄우기
type MyObject = {
readonly name : string,
}
let 철수 :MyObject = {
name : 'kim',
}
철수.name = 'Park'; // 에러
const는 변수 재할당이 불가능하지만, object의 내부 속성은 변경할 수 있다. 타입스크립트에서는 이것에 에러를 띄울 수 있다.
*** 중요한 사실 : JS로 컴파일 될 때 아예 변경을 막는 것은 아니고, 그냥 에러만 띄우는 것. 타입스크립트 에러는 에디터와 터미널에서만 존재한다.
type alias extend
type Name = string;
type Age = number;
type Person = Name | Age;
위처럼 타입 두개를 합쳐 타입 하나로 만드는 것도 물론 가능하다.
&연산자로 object 타입 extend (합치기)
type PositionX = { x : number };
type PositionY = { y : number };
type NewType = PositionX & PositionY;
let position :NewType = { x : 10, y : 20 };
** 주의사항 : 같은 이름의 type변수는 재정의가 불가능하다.
type 대신 interface
type 키워드 대신 interface 키워드를 사용해도 무방하다.
보통은 구조를 확장해야 할 때 interface를, 유니언이나 교차 타입을 사용하거나 타입을 조작해야 할 때 type을 사용하는 것이 일반적인 관례다.
interface PositionX {
x: number;
}
interface PositionY {
y: number;
}
type NewType = PositionX & PositionY;
let position: NewType = { x: 10, y: 20 };
** 주의사항 : 같은 이름의 type변수는 재정의가 불가능하지만 interface는 선언된 후에도 확장이 가능하다. 다른 곳에서 같은 이름의 interface를 선언하면 이전 선언과 병합된다.
& 대신 implements로 합치기
클래스나 객체가 interface를 구현할 때는 implements 키워드를 사용한다.
TypeScript에서 implements 키워드는 주로 클래스가 특정 인터페이스를 구현할 때 사용된다. implements는 클래스와 인터페이스 간의 관계를 선언하는데 사용되는 키워드이므로, 일반적으로 var, let, const 등의 변수 선언과 함께 사용되지 않는다.
interface Car {
start(): void;
stop(): void;
}
class ElectricCar implements Car {
start() {
console.log("Electric car is starting...");
}
stop() {
console.log("Electric car is stopping...");
}
chargeBattery() {
console.log("Charging the battery...");
}
}
const myElectricCar = new ElectricCar();
myElectricCar.start();
myElectricCar.stop();
myElectricCar.chargeBattery();
출처 : 코딩애플 https://codingapple.com/ / TypeScript Documentation https://www.typescriptlang.org/docs/handbook/2/objects.html
'📘 TypeScript > 개념' 카테고리의 다른 글
| [코딩애플] 타입스크립트 HTML 조작시 주의점 (1) (0) | 2023.12.17 |
|---|---|
| [코딩애플] 함수와 object 메서드에 type alias 지정하기 (0) | 2023.12.13 |
| [코딩애플] 타입을 특정 값으로 지정하자 : Literal Types (+ as const) (0) | 2023.12.13 |
| 타입스크립트 타입 유추(Type Inference) (0) | 2023.12.07 |
| [코딩애플] 타입스크립트 타입 지정 방법 (0) | 2023.12.07 |