728x90
반응형

만약 Object 타입을 지정해주려면 어떻게 해야 할까

 

먼저 TypeScript가 Object를 이해할 수 있게 해야 한다. 그리고 올바른 타입인지 검사해야 한다.

 

그러기 위해선 우리는 Interface를 써야한다. 먼저 아래와 같이 index.ts를 수정해보자.

 

 

index.ts

interface Human {
    name: string;
    gender: string;
    age: number;
}

const person = {
    name: "Teepo",
    gender: "male",
    age: 22
}

const sayHi = (person: Human):string => {
    return `Hello ${person.name}, you are ${person.age}, you are a ${person.gender}`
}

console.log(sayHi(person))

export {};

 

차근차근 하나씩 보자.

 

1. 먼저 interface 부분에서 해당 Object가 가지는 속성들의 타입을 지정해준다.

interface Human {
    name: string;
    gender: string;
    age: number;
}

 

 

 

2. 그 다음 실제 사용할 객체를 선언해준다.

const person = {
    name: "Teepo",
    gender: "male",
    age: 22
}

 

3. 함수를 선언할 때 인자로 들어오는 객체의 타입을 Human으로 지정해준다. ( 2번에 선언한 person과 상관없음 )

const sayHi = (person: Human):string => {
    return `Hello ${person.name}, you are ${person.age}, you are a ${person.gender}`
}

 

4. 실제 사용할 때 미리 선언해둔 객체를 넣어서 함수를 실행해준다. ( 이것이 2번에서 선언한 person )

console.log(sayHi(person))

 

 

이렇게 각각 속성들에 타입을 지정해주는 방법과 interface를 이용한 Object 타입 지정을 해보았다.

728x90
반응형

'Typescript > 이론' 카테고리의 다른 글

TypeScript | 이론 | Class  (0) 2021.10.05
TypeScript | 이론 | Types  (0) 2021.10.05
Typescript | 이론 | 세팅하기  (0) 2021.10.05

+ Recent posts