Typescript
Partial< T >
T타입 객체의 속성을 선택적으로 활용
=> 기존 타입의 일부 속성만 제공하는 객체 생성 가능
Required< T >
T타입 객체의 모든 속성이 정의돼야함.
ex) name?:string 과 같은 선택적 속성 불가
type RequiredPerson = Required<Person>;
interface DatabaseConfig {
host: string;
readonly port: number; //인터페이스도 사용 가능
}
const immutableConfig: Readonly<DatabaseConfig> = {
host: "localhost",
port: 3306,
};
interface Person {
name: string;
age: number;
address: string;
}
type SubsetPerson = Pick<Person, "name" | "age">;
interface Person {
name: string;
age: number;
address: string;
}
type SubsetPerson = Omit<Person, "address">;
객체 지향 프로그래밍
클레스 기반으로 생성되는 클래스의 인스턴스
class 키워드를 사용하여 정의
클래스에 속성과 메서드를 정의하고 new 키워드로 객체를 생성
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`안녕하세요! 제 이름은 ${this.name}이고, 나이는 ${this.age}살입니다.`);
}
}
const person = new Person('Spartan', 30);
person.sayHello();
클래스의 속성과 메서드에 접근 제한자를 통해 접근을 제한 가능
기존 클래스의 속성과 메서드를 물려받아 새로운 클래스를 정의
extends 키워드 사용
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log('동물 소리~');
}
}
class Dog extends Animal {
age: number;
constructor(name: string) {
super(name);
this.age = 5;
}
makeSound() {
console.log('멍멍!');
}
eat() { // Dog 클래스만의 새로운 함수 정의
console.log('강아지가 사료를 먹습니다.');
}
}
class Cat extends Animal { // Animal과 동일
}
const dog = new Dog('누렁이');
dog.makeSound(); //멍멍!
const cat = new Cat('야옹이');
cat.makeSound(); //동물 소리~
슈퍼타입
서브타입
any는 모든 것의 슈퍼타입
Animal은 Dog, Cat의 슈퍼타입
Dog, Cat은 Animal의 서브타입
서브타입을 슈퍼타입으로 변환
let animal: Animal = dog; // upcasting
animal.eat(); // 에러. 슈퍼타입(Animal)으로 변환이 되어 eat 메서드를 호출할 수 없음
캐스팅된 객체를 다시 원래의 서브타입으로 변환
as 키워드로 명시적으로 타입변환 필요
원래의 타입이 아니라면 런타임 에러가 발생
let animal: Animal;
animal = new Dog('또순이');
let realDog: Dog = animal as Dog;
realDog.eat(); // 서브타입(Dog)로 변환되어 eat 메서드를 호출rksmd
클래스와 달리 인스턴스화 할 수 없는 클래스
abstract class Shape {
abstract getArea(): number; // 추상 함수
printArea() {
console.log(`도형 넓이: ${this.getArea()}`);
}
}
class Circle extends Shape {
radius: number;
constructor(radius: number) {
super();
this.radius = radius;
}
getArea(): number { // 원의 넓이를 구하는 공식은 파이 X 반지름 X 반지름
return Math.PI * this.radius * this.radius;
}
}
class Rectangle extends Shape {
width: number;
height: number;
constructor(width: number, height: number) {
super();
this.width = width;
this.height = height;
}
getArea(): number { // 사각형의 넓이를 구하는 공식은 가로 X 세로
return this.width * this.height;
}
}
const circle = new Circle(5);
circle.printArea();
const rectangle = new Rectangle(4, 6);
rectangle.printArea();
추상 클래스를 상속 받은 자식 클래스는 반드시 추상 함수를 구현해야 함
객체가 가져아 하는 속성과 메서드 정의