본 글은 노마드코더의 TypeScript로 블록체인 만들기 강의를 보고 작성하는 글입니다.
Interface
const person = {
name: "Lee",
age: 22,
gender: "male",
};
const sayHi = (person): string => {
return `Hello ${person.name}, You are ${person.age} and ${person.gender}`;
};
console.log(sayHi(person));
export {};
index.ts
타입스크립트는 변수에 타입을 지정해서
변수에 들어가는 실제 자료가 변수의 자료형과 일치하는지 검사하는 역할을 한다고 했다.
그렇다면 object를 넘겨줄 때는 object가 내가 생각하는 object와 일치하는지 어떻게 검사를 할까?
위 코드를 보면 person이라는 매개변수를 받아서 person안의 name, age, gender를 표시해주는 코드이다.
만약 person에 name이나 gender가 없다면? 있어도 name이 숫자라면?
이를 방지하기 위해 즉, 타입스크립트가 객체의 타입을 체크하기 위해
일종의 객체의 설계도(객체의 자료형)를 적어두는 것을 interface라고 한다.
interface Human {
name: string;
age: number;
gender: string;
}
const person = {
name: "Lee",
age: 22,
gender: "male",
};
const sayHi = (person: Human): string => {
return `Hello ${person.name}, You are ${person.age} and ${person.gender}`;
};
console.log(sayHi(person));
export {};
index.ts
위 코드에서는 Human이라는 Interface를 작성하여 sayHi의 매개변수 person이 Human Interface임을 명시해주고 있다.
즉, 타입스크립트에서는 person에 들어오는 데이터를 Human과 동일한 형태를 갖고있는 데이터인지 검사할 것이다.
쉽게 말해 Interface란 객체의 형태를 제약하는 것이다.
이러한 interface는 JS로 컴파일되지 않는다.
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const person = {
name: "Lee",
age: 22,
gender: "male",
};
const sayHi = (person) => {
return `Hello ${person.name}, You are ${person.age} and ${person.gender}`;
};
console.log(sayHi(person));
//# sourceMappingURL=index.js.map
index.js
Class
Interface는 듣기에 Class와 비슷하다. 그러나 Class는 JS 코드에 포함된다는 차이가 있다.
React나 Vue와 같은 라이브러리를 사용할 경우 Interface가 아니라 Class를 사용해야할 수 있다.
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 lynn = new Human("Lynn", 18, "Female");
const sayHi = (person: Human): string => {
return `Hello ${person.name}, You are ${person.age} and ${person.gender}`;
};
console.log(sayHi(lynn));
export {};
index.ts
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Human {
constructor(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
const lynn = new Human("Lynn", 18, "Female");
const sayHi = (person) => {
return `Hello ${person.name}, You are ${person.age} and ${person.gender}`;
};
console.log(sayHi(lynn));
//# sourceMappingURL=index.js.map
index.js
또, Class에서는 public, private와 같은 접근 지정자를 지정해줄 수 있는데
이는 JS에는 존재하지 않는 것으로 js파일에는 포함되어 있지 않다.
접근 지정자의 다른 예로 위 코드에서 age의 접근 지정자를 private로 변경한다면
src/index.ts(15,50): error TS2341: Property 'age' is private and only accessible within class 'Human'.
오전 6:31:31 - Found 1 error. Watching for file changes.
쉘에서 다음과 같은 에러를 뱉어낼 것이다.
'Frontend > TypeScript' 카테고리의 다른 글
[TS] 제너릭 (0) | 2022.02.28 |
---|---|
[TS] export/import & type-only export/import (0) | 2022.02.28 |
[TS] 타입 스크립트의 타입 (0) | 2022.02.28 |
[TS] TypeScript Install & Setting (0) | 2022.02.28 |