본문 바로가기

TS

TypeScript - object, Interface, class

강의 링크

 

이전까지는 아래와 같은 코드로 argument를 하나 하나 직접 주고 param의 type를 하나하나 지정해주었다.

const sayHi = (name:string, age:number, city:string): string => {
  return `Hello ${name}, you are ${age} old and from ${city}.`;
}

console.log(sayHi('Joe', 24, 'Seoul'));

export {};

여기서 argument로 object를 넘기게 하고 싶다. 일단 object를 만들어서 넣어보면 argument가 모자르다고 에러가 난다.

함수의 param을 object를 받는 것으로 바꾸고, 이 object의 type을 interface로 지정해줘야 된다. ts는 person이 Human interface와 같은 구조를 갖고 있는지 확인한다.

interface Human {
  name: string;
  age: number;
  city: string;
}
  
const person = {
  name: 'Joe',
  age: 24,
  city: 'Seoul'
};
  
const sayHi = (person: Human):string => {
  return `Hello ${person.name}, you are ${person.age} old and from ${person.city}.`;
}
  
console.log(sayHi(person));
  
export {}; 

interface는 JS에서 작동하지 않는다.

이 대신 class를 쓰는데, class가 가져야 되는 속성들과 그 속성들이 갖고 있는 권한을 넣어줘야 된다.

JS 파일에서 public/private은 없다.

class Human {
  public name: string;
  public age: number;
  public city: string;
  constructor(name: string, age: number, city: string) {
    this.name = name;
    this.age = age;
    this.city = city;
  }
}
  
const person = new Human('Joe',24,'Seoul');

const sayHi = (person: Human):string => {
  return `Hello ${person.name}, you are ${person.age} old and from ${person.city}.`;
}
  
console.log(sayHi(person));
  
export {}; 

'TS' 카테고리의 다른 글

TypeScript - TS to JS  (0) 2021.03.15