interface Shape {
getArea(): number;
}
getArea 함수가 정의될 것이고 그 함수는 number를 반환할 것이다.
간편하게 쓰는 방법
class Circle implements Shape {
constructor(private radius: number) {}
getArea() {
return this.radius * this.radius * Math.PI;
}
}
어렵게 쓰는 방법
class Circle implements Shape {
private radius: number;
constructor(radius: number) {
this.radius = radius;
}
getArea() {
return this.radius * this.radius * Math.PI;
}
}
두개 다 compile해서 파일을 비교해봤는데 차이가 없더라. 두개 다 아래처럼 나온다. 즉, 쉽게 쓰는 방법을 쓰자.
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Circle {
constructor(radius) {
this.radius = radius;
}
getArea() {
return this.radius * this.radius * Math.PI;
}
}
const circle = new Circle(5);
console.log(circle.getArea());
public과 private은 typescript 내부에서만 의미있다고 보면 된다. compile해서 만든거 보면 public으로 했을 때나 private으로 했을 때나 같은 코드가 나온다.
interface Person {
name: string;
age: number;
}
interface Developer extends Person {
skills: string[];
}
const taejoon: Person = {
name: 'taejoon',
age: 30,
};
const FEDeveloperTaejoon = {
name: 'taejoon',
age: 30,
skills: ['js', 'css', 'html'],
};
extends
를 이용해서 반복되는 type선언을 상속받았다. 그래서 중복코드를 줄일 수 있게 되었다.
부를 때는 type alias
라고 부른다.
type을 이용해서 interface와 동일하게 할 수 있다. 바로 위 예시를 토대로 type으로 바꿔보자.
type Person = {
...
}
type Developer = Person & {
...
}
...
type People = Person[] // People이란 type에 뿌리인 Person type을 배열로 선언한다.
const people: Person = [taejoon, FEDeveloperTaejoon];
type Color = 'red' | 'orange' | 'yellow';
const color: Color = 'red';
벨로퍼트님의 타입스크립트 강좌를 보고 정리한 내용입니다.