TypeScript Study 02

JeongInu·2025년 4월 3일
0

TypeScript Study

목록 보기
2/4

TypeScript Study 02

노마드코더 타입스크립트 강의 정리

Overloading

하나의 함수가 여러개의 호출 방식(Call Signature)을 가짐
같은 함수 이름이지만 매개변수나 반환 타입이 다를 수 있는 함수를 정의

  • Call Signature
    - 함수의 매개변수 타입과 반환 타입읠 정의
type FuncSignature = (param: string) => number;

FuncSignature는 매개변수로 String을 받아 number를 반환하는 함수 타입을 정의한 것

function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any{
  return a+b;
}

console.log(add(10, 20));		//30
console.log(add("Hello,", "Wrold!"));		// "Hello, World!"

이렇게 하면 타입스크립트는 함수 호출 시 number / string 중 뭘 전달했는지 체크하고 올바르게 동작하도록 유도
-> 하나의 함수가 여러개의 타입을 처리해야 할 때

type Add = {
    (a: number, b: number): number
    (a: number, b: string): number
}

const add: Add = (a, b) => {
    if(typeof b === "string") return a
    return a + b
}

type Config = {
    path: string,
    state: object
}

type Push = {
    (path: string): void
    (config: Config): void
}

const push: Push = (config) => {
    if(typeof config === "string"){
        console.log(config)
    }else{
        console.log(config.path)
    }
}

type Add = {
    (a: number, b: number): number
    (a: number, b: number, c: number): number,
}

const add: Add = (a, b, c?:number) => {
    if(c) return a + b + c
    return a + b
}

add(1, 2)
add(1, 2, 3)

Polymorphism(다형성)

  • 하나의 인터페이스나 클래스가 여러 타입을 가질 수 있는 개념
  • 같은 메서드라도 다른 방식으로 동작할 수 있도록 만드는 것
  • 제네릭(Generic) 다형성 / 인터페이스 다형성 / 상속(클래스 다형성)

제네릭

  • 같은 함수나 클래스를 여러 타입에서 재사용 가능하도록 만드는 방법
function identity<T>(value: T):T {
  return value;
}

console.log(identity<number>(10));		//10
console.log(identity<string>("Hello"));		// "Hello"
- identity<T> 는 T라는 제네릭 타입을 받아 반환
- 같은 함수를 다양한 타입에서 사용 가능

인터페이스

  • 인터페이스를 사용하면 다양한 객체에서 공통된 규칙을 따르게 하면서, 서로 다른 구현을 가질 수 있음
interface Animal{
    makeSound(): void;
}

class Dog implements Animal{
    makeSound(){
        console.log("멍멍!");
    }
}

class Cat implements Animal{
    makeSound(){
        console.log("야옹~");
    }
}

const animals: Animal[] = [new Dog(), new Cat()];

animals.forEach(animal => animal.makeSound());
  • Dog과 Cat은 Animal 인터페이스를 구현, makeSound 메서드를 각자 다르게 수행

상속

  • 부모 클래스를 상속받아 자식 클래스에서 다른 동작을 정의
class Vehicle{
    move(){
        console.log("이동 수단입니다.");
    }
}

class Car extends Vehicle{
    move(){
        console.log("뛰뛰빵빵");
    }
}

class Airplane extends Vehicle{
    move(){
        console.log("슈우웅");
    }
}

const vehicles: Vehicle[] = [new Car(), new Airplane()];
  • 같은 코드로 다양한 객체를 다룰 수 있도록 하는 개념
    • 유지보수성 증가
    • 코드 재사용성 증가
    • 확장성 뛰어남
type SuperPrint = {
    <TypePlaceholder>(arr: TypePlaceholder[]): void
}

const superPrint: SuperPrint = (arr) => {
    arr.forEach(i => console.log(i));
}

superPrint([1, 2, 3, 4])
superPrint([true, false, true])
superPrint(["a", "b", "c"])
superPrint([1, 2, true, false])

// 알아서 number|boolean으로 처리

type SuperPrint = {
    <TypePlaceholder>(arr: TypePlaceholder[]): TypePlaceholder
}

const superPrint: SuperPrint = (arr) => arr[0]

superPrint([1, 2, 3, 4])
superPrint([true, false, true])
superPrint(["a", "b", "c"])
superPrint([1, 2, true, false, "hello"])
// 출력까지 알아서 처리

type SuperPrint = {
    (a: any[]): any
}

const superPrint: SuperPrint = (a) => a[0]

const a = superPrint([1, 2, 3, 4])
const b = superPrint([true, false, true])
const c = superPrint(["a", "b", "c"])
const d = superPrint([1, 2, true, false, "hello"])

d.toUpperCase();
// any를 사용해도 당장은 에러가 발생하지 않지만 출력값에 따라 에러 가능성이 있다.

0개의 댓글