npm install classnames
true일 때 class추가해주는 것은 classnames라이브러리를 이용하여 가독성을 높인다.
// 사용전
<div className={`box ${red ? 'red' : ''}`} />
// 사용후
import cx from "classnames";
<div className={cx(box, {red: red})} />
interface Student {
name: string;
age: number;
}
const gildong: Student = {
name: '고길동',
age: 42,
};
//
type Student= {
name: string;
age: number;
};
const kiyoung: Student = {
name: '김기영',
age: 18,
};
함수 정의시 syntax차이가 있다.
Interface
interface Point {
x: number;
y: number;
}
interface SetPoint {
(x: number, y: number): void;
}
Type alias
type Point = {
x: number;
y: number;
};
type SetPoint = (x: number, y: number) => void;
// primitive
type Name = string;
// object
type PartialPointX = { x: number; };
type PartialPointY = { y: number; };
// union
type PartialPoint = PartialPointX | PartialPointY;
// tuple
type Data = [number, string];
extend시 syntax차이가 있다. + 상호 배타적이지 않다
Interface extends interface
interface PartialPointX { x: number; }
interface Point extends PartialPointX { y: number; }
Type alias extends type alias
type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };
Interface extends type alias
type PartialPointX = { x: number; };
interface Point extends PartialPointX { y: number; }
Type alias extends interface
interface PartialPointX = { x: number; }
type Point = PartialPointX & { y: number; };
interface에서 유니온 type alias implements는 불가능
interface Point {
x: number;
y: number;
}
class SomePoint implements Point {
x = 1;
y = 2;
}
type Point2 = {
x: number;
y: number;
};
class SomePoint2 implements Point2 {
x = 1;
y = 2;
}
type PartialPoint = { x: number; } | { y: number; };
// FIXME: can not implement a union type
class SomePartialPoint implements PartialPoint {
x = 1;
y = 2;
}
5. Declaration merging
Unlike a type alias, an interface can be defined multiple times, and will be treated as a single interface (with members of all declarations being merged).
// These two declarations become:
// interface Point { x: number; y: number; }
interface Point { x: number; }
interface Point { y: number; }
const point: Point = { x: 1, y: 2 };
TypeScript 팀은 확장에 열려있는 JavaScript 객체의 동작 방식과 비슷하게 연결하도록 Interface를 설계했다.
추가로 interface는 동일한 이름으로 여러번 선언해도 확장이 정상적으로 작동
튜플 사용시에만 type을 사용한다.