Language/Typescript

타입 정의

Jinn 2023. 12. 19. 20:02

변수나 인수이름 뒤에 타입 애너테이션을 붙여서 타입을 정의할 수 있다.

 

변수
const name: string = 'Jin';
const age: number = 25;

 

배열
const names: string[] = ['Jin', 'Hana'];
const = ages: number[] = [25, 24];

 

 

객체
const user: { name: string, age: number } = {
    name: 'Jin',
    age: 25
}

 

함수
function greeting(name: string): string {
    return `Hello ${name}`;
}

 

const greeting = (name: string): string => `Hello ${name}`

 


타입 추론(Type Inference)

명시적인 변수 초기화를 수행하면 타입 추론을 통해 자동으로 타입이 결정됨.

const name = 'Jin';
const age = 25;

 

name에는 string 리터럴, age에는 number 리터럴이 초기화 되었으므로 타입 추론을 통해 name과 age에는 각각 string과 number로 타입이 결정된다.

 

const names = ['Jin', 'Hana']; // names의 타입이 string[]으로 정해진다.

 

타입 별명(Type Alias)

타입 정의에 이름을 붙이고 이를 참조해서 같은 타입을 여러 번 사용할 수 있다.

type Point = {
    x: number;
    y: number;
}

function printPoint(point: Point) {
    console.log(`x 좌표는 ${point.x}`);
    console.log(`y 좌표는 ${point.y}`);
}

printPoint({x: 100, y: 200});

 

Union 타입
const ages: (number | string)[] = [25, '24'];

 

Union 타입은 여러 타입을 조합하여 사용할 수 있게 한다. ages 배열은 number와 string 두 타입을 모두 허용한다.

 

type CookieWithCompany = {
    name: string;
    company: string;
}

type CookieWithTaste = {
    name: string;
    taste: string;
}

type Cookie = CookieWithCompany | CookieWithTaste;

const firstCookie: Cookie = Math.random() > 0.5 ? {name: 'OREO', company: 'Nabisco'} : {name: 'OREO', taste: 'Choco'};

firstCookie.name; // 공통 속성인 name은 접근 가능

// 접근 불가능
firstCookie.company;
firstCookie.taste;

// Narrowing
if ('company' in firstCookie) firstCookie.company;
else if ('taste' in firstCookie) firstCookie.taste;