[Typescript]

홍예찬·2021년 2월 16일
1
post-thumbnail

What is typescript?

타입스크립트는 자바스크립트의 superset으로 자바스크립트를 기반으로 하는 언어이자 라이브러리입니다.
자바스크립트를 통해서도 코딩을 할 수 있는데 굳이 타입스크립트를 쓰는 이유는 뭘까요?
그 이유는 자바스크립트가 동적 언어이기 때문입니다.
그렇기에 자바스크립트 기반의 대규모 프로젝트를 진행하거나 여러 개발자들과 협업을 하게 되면, 내가 작성하지 않은 함수를 사용하는 경우, 예상과는 다른 값을 리턴하는 상황을 마주할 수 있게 됩니다.
typescript를 통해 데이터 타입을 명시적으로 지정하게 되면, 불필요한 에러를 방지할 수 있다는 강력한 장점을 지니게 되는 것이죠!

기본적인 Type

기본적인 타입 명시는 다음과 같습니다. 함수의 경우에도 리턴되는 값의 타입을 지정할 수 있습니다.
(함수가 아무 값도 리턴하지 않는 경우 void를 사용합니다.)


let studentId : number = 123456;
let studentName : string = 'Jacob';
let courseCompleted : boolean = true;

// 1. 함수의 리턴 값의 타입이 객체인 경우 
function getStudentDetails(studentId: number):object {
    return {studentId, studentName, courseCompleted};
}

// 2. object로 타입을 명시하는 경우 타입의 범위가 너무 넓기 때문에 실제 반환하는 객체의 구조에 타입을 지정
function getStudentDetails(studentId: number): {
    studentId: number;
    studentName: string;
    courseCompleted: boolean;
} {
    return {studentId, studentName, courseCompleted}
}

2번의 경우 리턴된 값들의 타입 범위를 좁힐 수 있지만 만약 들어가는 타입의 종류가 많아지게 된다면 가독성이 떨어지게 됩니다. 이 때, interface를 사용하게 됩니다.


Interface

인터페이스를 타입으로 가지는 값은 인터페이스의 구조를 그 값으로 가지도록 강제됩니다.
만약 리턴되는 값 중에서 필수적이지 않은 프로퍼티의 경우에는 optional 기호 ?를 사용하면 됩니다.


// compile error!
interface Student {
    studentId: number;
    studentName: string;
    courseCompleted: boolean;
}

function getStudentDetails(studentId: number): Student {
    return {studentId, studentName}
}

//optional 기호를 사용한 경우
interface Student {
    studentId: number;
    studentName: string;
    courseCompleted?: boolean;
}

function getStudentDetails(studentId: number): Student {
    return {studentId, studentName }
}

enum

열거형으로 숫자값 집합에 이름을 지정한 것입니다.


enum GenderType {
    Male,
    Female
}

interface Student {
    studentId: number;
    studentName: string;
    courseCompleted?: boolean;
    gender: GenderType 
}

function getStudentDetails(studentId: number): Student {
    return {studentId, studentName: 'Jacob', courseCompleted:true, gender: GenderType.Female }
}

getStudentDetails(12345)

literal type


interface Student {
    studentId: number;
    studentName: string;
    courseCompleted?: boolean;
    gender: 'male' | 'female'
}

function getStudentDetails(studentId: number): Student {
    return {studentId, studentName: 'Jacob', courseCompleted:true, gender: 'male'}
}

getStudentDetails(12345)

union

제한된 타입들을 동시에 지정하려 할 때 사용하는 타입입니다.


let price: number | string = 5;
price = 'free'
price = true; //compile error!

Type Aliases

같은 타입의 조합이 지속적으로 반복될 경우 코드를 타입으로 지정하고 재활용할 때 사용하게 됩니다.


let orderId: number | string;

const calculateTotalCost = (price: number | string, qty:number):void => {
    
};

const findeOrderID = (customer: {customerID: number | string, name: string}) : number | string => {
    return orderId
}
type strOrNum = number | string;

let totalCost: number;
let orderId: strOrNum;

const calculateTotalCost = (price: strOrNum, qty:number):void => {
    
};

const findeOrderID = (customer: {customerID: strOrNum, name: string}) : strOrNum => {
    return orderId
}

Type Guard

union 타입을 사용하게 될 때 typeof operator를 사용함으로써 코드 검증을 수행합니다.
(typeof operator이외에도 다양한 방식이 여기에 있습니다.)


type strOrNum = number | string;
let itemPrice: number;

const setItemPrice = (price: strOrNum):void => {
    if(typeof price === 'string') {
        itemPrice = 0;

    }else {
        itemPrice = price;
    }
};

profile
내실 있는 프론트엔드 개발자가 되기 위해 오늘도 최선을 다하고 있습니다.

0개의 댓글