enum Status {
NotFound = 404,
Success = 200,
}
숫자 대신 이름으로 의미를 표현할 수 있다.
사용자 정의 이름으로 유형을 정의할 수 있다.
type CarYear = number
type CarType = string
type CarModel = string
type Car = {
yaer: CarYear,
type: CarType,
model: CarModel
}
const carYear: CarYear = 2001
const carType: CarType = "Toyota"
const carModel: CarModel = "Corolla";;;
객체의 모양을 정의하기 위해 사용된다. 객체가 어떤 속성과 타입을 가져야 하는지 약속
interface User {
name: string;
age: number;
}
const user:User = {
name: "Alice",
age: 25
};
= 타입 안정성, 가독성 향상, 재사용성, 확장성
인터페이스틑 서로 상속할 수 있다.
1) interface : 객체의 구조, 클래스 설계, API응답 형태 등을 표현할 때
여러 인터페이스를 상속해서 조합할 때, 외부 모듈 사용
2) 합집합, 교집합, 기본형 등을 표현할 때, 조건부 타입을 쓸 때
type ID = string | number; // 합집합
type Point = { x: number } & { y: number }; // 교집합
type ID = string | number; // 합집합
type Point = { x: number } & { y: number }; // 교집합
function printStatusCode(code: string | number) {
console.log(`My status code is ${code}.`)
}
printStatusCode(404);
printStatusCode('404');
function getTime(): number {
return new Date().getTime();
}
void함수가 아무 값도 반환하지 않음을 나타내는 데 사용할 수 있다.
function printHello(): void {
console.log('Hello!');
}
function multiply(a: number, b: number) {
return a * b;
}
function pow(value: number, exponent: number = 10) {
return value ** exponent;
}
function add(a: number, b: number, ...rest: number[]) {
return a + b + rest.reduce((p, c) => p + c, 0);
}
변수의 유형을 재정의 해야 하는 경우
let x: unknown = 'hello';
console.log((x as string).length);
let x: unknown = 'hello';
console.log((<string>x).length);
let somwValue: unknown = "hello world";
let strLength: number = (someValue as string).length;
class Person {
name: string;
}
const person = new Person();
person.name = "Jane";
public- (기본값) 어디에서나 클래스 멤버에 액세스할 수 있습니다.
private- 클래스 내부에서만 클래스 멤버에 대한 액세스를 허용합니다.
protected- 상속 섹션에서 다루는 내용에 따라 자체 및 이를 상속하는 모든 클래스에서 클래스 멤버에 대한 액세스를 허용합니다.
class Person {
// name is a private member variable
public constructor(private name: string) {}
public getName(): string {
return this.name;
}
}
const person = new Person("Jane");
console.log(person.getName());
클래스 멤버가 변경되는 것을 방지 가능
클래스와 인터페이스
인터페이스의 형태를 따라감(계약을 지킴)
interface Shape {
getArea: () => number;
}
class Rectangle implements Shape {
public constructor(protected readonly width: number, protected readonly height: number) {}
public getArea(): number {
return this.width * this.height;
}
}
클래스는 클래스와 인터페이스는 인터페이스 부모의 속성과 메서드를 물려받는다.
클래스는 키워드를 통해 서로를 확장할 수 있다. extends
class Animal {
move() {
console.log("동물이 움직입니다");
}
}
class Dog extends Animal {
bark() {
console.log("멍멍!");
}
}
const d = new Dog();
d.move(); // 부모 클래스의 메서드 사용 가능 ✅
d.bark();
클래스가 다른 클래스를 확장하는 경우, 같은 이름을 가진 부모 클래스의 멤버를 대체할 수 있다.
// 이미 Rectangle 클래스가 있다고 가정
class Square extends Rectangle {
public constructor(width: number) {
super(width, width);
}
public override toString(): string {
return `Square[width=${this.width}]`; // 대체
}
}
모든 멤버를 구현하지 않고 다른 클래스의 기본 클래스로 사용될 수 있도록 작성 가능
abstract class Polygon {
public abstract getArea(): number;
public toString(): string {
return `Polygon[area=${this.getArea()}]`;
}
}