Misc/백엔드

NodeJs Backend REST API (1) - Typescript

foreverWon 2024. 7. 3. 18:22
목차

    <Typescript>

    1. 기본 타입

    number 숫자
    string 문자열
    boolean T/F
    null  
    undefined 타입이 정의되지 않은 타입
    any 모든 타입, API같은 외부 자원을 활용해 개발 시 타입을 단언할 수 없는 경우 유용
    never 절대 발생하지 않을 값, 어떠한 타입도 적용 X
    void 값을 반환하지 않는 함수에서 사용
    object 객체 

    2. Type의 조합

    type Person = {
        name: string
        age: number
    }
    let kim: Person

    3. Union

    • 2개 이상의 타입을 허용하는 경우
    let test: number|string
    
    type Student = {
        name: string
        age: number
        major: string
    }
    type Worker = {
        name: string
        age: number
        skill: string
    }
    
    funtion fn(param: Student|Worker): void{
        ...
    }

     4. Interface

    • 속성의 확장(extends) 가능
    • 여러 타입 extends 가능
    interface Person {
        name: string
        age: number
    }
    
    interface Student extends Person {
        major: string
    }
    
    interface Worker extends Person {
        skill: string
    }
    
    interface Programmer extensd Worker, Studnet {
        ...
    }

    5. Function

    function Sum(num1: number, num2: number):number {
        return num1+num2
    }
    
    function Sum(num1: number, num2: number):void {
        console.log(num1+num2)
    }

    6. Generics

    • 특정 함수에서 매개변수나 리턴값이 상황에 따라 동적으로 타입이 달라지는 경우 유용

    1) 기본 문법

    function 함수명<타입 변수>(매개변수: 타입 변수): 반환 타입 {
        /* 함수 본문 */
    }
    function identify<T>(arg: T): T {
        return arg;
    }
    
    identify<string>('hi')
    identify<number>(10)
    identify<boolean>(true)
    function logText(text: string|number) {
        console.log(text)
        return text
    }
    
    const num = logText(1)
    const a = logText('a')
    a.toUpperCase() // 오류 표시
    //toUpperCase는 문자타입에만 적용 가능한데 해당 함수가 문자나 숫자 타입 둘 다 가능하기 때문에 오류 발생
    
    // 수정
    function logText<T>(text: T): T {
        console.log(text)
        return text
    }
    
    const str = logText<string>('abc') // 타입을 string으로 지정
    str.toUpperCase() // 정상 작동

    2) 배열

    function identify<T>(arg: T[]): T[] {
        return arg.length
    }
    // 또는
    function identify<T>(arg: Array<T>): Array<T> {
        retun arg.length
    }

    3) Interface

    interface GenericFn<T> {
        (arg: T): T
    }
    
    function identity<T>(arg: T): T {
        return arg
    }
    let myIdentity: GenericFn<number>=identy

    4) Promise

    async function test<T>(arg: T): Promise<T> {
        await new Promise((resolve) => setTimeout(resolve, 1000))
        return arg
    }

    서버 통신 등에 필수로 사용되는 Promise는 Generic이 항상 사용된다.

    7. TypeGuard

    • 원하지 않는 타입에 의한 오류가 발생하지 않게 하는 것
    function testGuard(value: number|string) {
        value.toFixed() // 오류
        ...
    }
    // 숫자형 타입만 toFixed()로 반올림이 가능하므로 오류 발생
    
    // 수정
    function testGuard(value: number|string) {
        if(typeof value = 'number') { // 특정 타입일 때만 기능이 실행되도록 함
        value.toFixed()
        }
    }
    type Dog = {
        name: string
        color: string
    }
    
    function testGuard(value: Dog) {
        if('color' in value) {
            console.log('color는 ${value.color} 입니다.')
        }
    }

    직접 만든 type에서 타입 확인이 필요할 경우 in을 사용하여 어떤 속성이 있는지 확인 가능하다. 

    타입 가드가 정확히 지켜지지 않으면 오류가 표시되므로 매개변수로 사용되는 값이 가변적일 때는 타입가드를 신경 써야 한다.

     

     

     

    Reference
        
        https://www.youtube.com/watch?v=1SgjVUScafw&list=PLEU9vwKdoCqR9yTVGnfq1tIu5wPraKDV-&index=2

     

     

     

     

    728x90

    'Misc > 백엔드' 카테고리의 다른 글

    NodeJs Backend REST API (3) - Prisma  (0) 2024.07.13
    NodeJs Backend REST API (2) - Fastify  (0) 2024.07.03
    HTTP  (0) 2024.06.25
    API  (0) 2024.06.25
    백엔드의 전체 흐름  (0) 2024.06.24