아래의 영상을 보고 개인적으로 정리한 글입니다
링크 : 노마드 코더의 타입스크립트 강의
// index.ts
interface Human {
name: string,
age: number,
gender: string,
}
const person = {
name: "nicolas",
gender: "male",
age: 22,
}
const sayHi = (person: Human): string => {
return `Hello ${name}, you are ${age}, you are a ${gender}`;
}
console.log(sayHi(person));
export {};
블록체인 파트로 들어가기 전 inteface 사용법에 대해 매우 짧게 알아보는 시간을 가졌다.(실제 강의 시간도 4분여 남짓...)
짧게 정리하자면...
내가 넘겨줄 Object 객체가 가진 property 에 대해 interface 를 작성하고 interface 안에 각각의 property 에 대한 타입을 정의해준다.
sayHi 함수의 인자로 person 을 넣을 때 type 을 Human 으로 정의함으로써 person 객체가 어떤 property 와 각각의 property 에 대해 어떤 type 을 가졌는지 알 수 있다.
또한 inteface 는 js 로 컴파일 되지 않는다.
// dst/index.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const person = {
name: "nicolas",
gender: "male",
age: 22,
};
const sayHi = (person) => {
return `Hello ${person.name}, you are ${person.age}, you are a ${person.gender}`;
};
console.log(sayHi(person));
//# sourceMappingURL=index.js.map
타입을 명시하고 interface 가 컴파일 된 모습을 보고 싶다면 class 방식으로 작성할 수 있다.
// src/index.ts
class Human {
public name: string;
public age: number;
public gender: string;
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
const person = new Human('nicolas', 24, 'male');
const sayHi = (person: Human): string => {
return `Hello ${person.name}, you are ${person.age}, you are a ${person.gender}`;
}
console.log(sayHi(person));
export {};
위 코드를 컴파일 해보면 아래와 같이 클래스를 사용하는 것을 볼 수 있다.
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Human {
constructor(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
const person = new Human('nicolas', 24, 'male');
const sayHi = (person) => {
return `Hello ${person.name}, you are ${person.age}, you are a ${person.gender}`;
};
console.log(sayHi(person));
//# sourceMappingURL=index.js.map
상황에 맞게 interface 또는 class 를 적절하게 사용하면 될 것 같은데 개인적으로는 inteface 가 많이 편한 것 같다.