TypeScript
클래스
class Person {
private name: string;
public constructor(name: string) {
this.name = name;
}
public getName(): string {
return this.name;
}
}
const person = new Person("Jane");
console.log(person.getName());
Implements - 인터페이스 상속
- 인터페이스는 생성자 객체를 가지지 않으며, 규격만 정의
- 인터페이스는 클래스가 다중 상속이 가능
- 인터페이스들끼리의 상속은 extends 키워드로 가능
interface Shape {
getArea: () => number;
}
class Rectangle implements Shape {
// 생성자에 private 또는 protected 접근 지정자로 로컬 변수를 설정하면 멤버 변수로 설정 가능
public constructor(
protected readonly width: number,
protected readonly height: number
) {}
public getArea(): number {
return this.width * this.height;
}
public toString(): string {
return `Rectangle[width=${this.width}, height=${this.height}]`;
}
}
const myRect = new Rectangle(10, 20);
console.log(myRect.getArea());
Extends - 클래스 상속
- 클래스 상속 시, supter 생성자 반드시 호출
- 클래스는 다중 상속 불가능
class Square extends Rectangle {
public constructor(width: number) {
super(width, width); // 부모 클래스 생성자
}
}
const mySq = new Square(20);
console.log(mySq.getArea());
오버라이딩
슈퍼 클래스 메서드를 서브 클래스에서 내용을 달리하여 채우는 것
class Square extends Rectangle {
public constructor(width: number) {
super(width, width);
}
// 오버라이딩
public override toString(): string {
return `Square[width=${this.width}]`;
}
}
console.log(myRect.toString());
console.log(mySq.toString());
추상 클래스
- 다른 클래스가 파생될 수 있는 기본 클래스
- 메모리에 올라갈 수 없어 직접 인스턴스를 생성할 수 없기 때문에 파생된 후손 클래스에서 인스턴스 생성해야 함
- 추상 클래스를 상속 받는 클래스는 추상 메소드를 구현할 책임을 가짐
- 인터페이스와 굉장히 유사하며, 다른 점은 속성이나 메소드 멤버에 대한 세부 구현 가능
abstract class Polygon {
public abstract getArea(): number;
public toString(): string {
return `Polygon[area=${this.getArea()}]`;
}
}
class Rectangle3 extends Polygon {
public constructor(
protected readonly width: number,
protected readonly height: number
) {
super();
}
public getArea(): number {
return this.width * this.height;
}
}
const myRect2 = new Rectangle3(10, 20);
console.log(myRect2.getArea());
제네릭
- 동적으로 타입 결정
function createPair<S, T>(v1: S, v2: T): [S, T] {
return [v1, v2];
}
console.log(createPair<string, number>("hello", 42));
console.log(createPair("hello", 42)); // 타입 추론 활용
타입 별칭
type Wrapped<T> = { value: T };
const wrappedValue: Wrapped<number> = { value: 10 };
확장
unction createLoggedPair<S extends string | number, T extends string | number>( // string과 number 타입만 허용
v1: S,
v2: T
): [S, T] {
console.log(`v1 = ${v1}, v2 = ${v2}`);
return [v1, v2];
}
console.log(createLoggedPair("hello", 42));
유틸리티 타입
Partial
객체의 모든 속성을 선택 사항으로 변경
function createLoggedPair<S extends string | number, T extends string | number>( // string과 number 타입만 허용
v1: S,
v2: T
): [S, T] {
console.log(`v1 = ${v1}, v2 = ${v2}`);
return [v1, v2];
}
console.log(createLoggedPair("hello", 42));
Required
객체의 모든 속성을 필수로 변경
interface Car {
make: string;
model: string;
mileage?: number;
}
let myCar: Required<Car> = {
make: "Ford",
model: "Focus",
mileage: 12000, // Required 타입이므로 무조건 정의
};
Record
특정 키 유형과 값 유형으로 객체 유형의 정의
const nameAge: Record<string, number> = {
Alice: 21,
Bob: 25,
};
Pick
지정된 key만 남기고 나머지는 객체 유형에서 제거
interface Person2 {
name: string;
age: number;
location?: string;
}
const bob1: Pick<Person2, "name"> = {
name: "Bob",
};
Omit
객체 유형에서 키를 제거
interface Person3 {
name: string;
age: number;
location?: string;
}
const bob2: Omit<Person3, "age" | "location"> = {
name: "Bob",
};
Exclude
타입 1에서 타입2를 제외한 새로운 타입 반환
type Primitive = string | number | boolean;
const value: Exclude<Primitive, string> = true;
const value2: Exclude<Primitive, string> = "true"; // Error
ReturnType
함수 유형의 반환 유형을 추출
type PointGenerator = () => { x: number; y: number };
const point: ReturnType<PointGenerator> = {
x: 10,
y: 20,
};
Parameters
매개변수 유형을 배열로 추출
type PointPrinter = (p1: { x: number; y: number }, p2: { z: number }) => void;
const point2: Parameters<PointPrinter>[1] = {
z: 20,
};
console.log(point2);
Readonly
모든 속성이 읽기 전용인 새로운 유형을 생성
interface Person4 {
name: string;
age: number;
}
const person4: Readonly<Person4> = {
name: "Dylan",
age: 35,
};
person.name = "Israel"; // Error
Keyof
- 인덱싱이 가능한 타입에서 keyof를 사용하면 속성 이름으로 타입 사용 가능
interface Person5 {
name: string;
age: number;
}
function printPersonProperty(person: Person5, property: keyof Person5) {
console.log(`${property}: "${person[property]}"`);
}
let person5 = {
name: "Max",
age: 27,
};
printPersonProperty(person5, "name");
Null
Optional Chaining
필수가 아닌 속성으로 정의
interface House {
sqft: number;
yard?: {
sqft: number;
};
}
function printYardSize(house: House) {
const yardSize = house.yard?.sqft;
if (yardSize === undefined) {
console.log("No yard");
} else {
console.log(`Yard is ${yardSize} sqft`);
}
}
let home: House = {
sqft: 500,
};
printYardSize(home); // No yard
Nullish Coalescence
null과 undefined가 아니라면 앞의 내용을, 맞다면 뒤의 내용을 출력
function printMileage(mileage: number | null | undefined) {
console.log(`Mileage: ${mileage ?? "Not Available"}`);
}
printMileage(null); // Not Available
printMileage(0); // 0
Null Assertion
해당 피연산자가 null, undefined가 아니라고 단언
function getValue(): string | undefined {
return "hello";
}
let value = getValue();
console.log('value length: ' + value!.length);
728x90
반응형
'LG 유플러스 유레카 SW > TypeScript' 카테고리의 다른 글
[#7] TypeScript 익히기(1) (1) | 2025.02.04 |
---|