[원티드] 5월 7일 TIL

eaasurmind·2022년 5월 7일
0

TIL

목록 보기
4/27

classnames 라이브러리


npm install classnames

true일 때 class추가해주는 것은 classnames라이브러리를 이용하여 가독성을 높인다.

 // 사용전
  <div className={`box ${red ? 'red' : ''}`} />

// 사용후

import cx from "classnames";

<div className={cx(box, {red: red})} />

Type Alias & Interface


interface Student {
  name: string;
  age: number;
}

const gildong: Student = {
  name: '고길동',
  age: 42,
};

//

type Student= {
  name: string;
  age: number;
};

const kiyoung: Student = {
  name: '김기영',
  age: 18,
};
  1. Objects / Functions

함수 정의시 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;
  1. Other Types
    type alias는 원시타입, 유니온, 튜플 사용이 가능

// primitive
type Name = string;

// object
type PartialPointX = { x: number; };
type PartialPointY = { y: number; };

// union
type PartialPoint = PartialPointX | PartialPointY;

// tuple
type Data = [number, string];
  1. Extend
    Both can be extended, but again, the syntax differs. Additionally, note that an interface and type alias are not mutually exclusive. An interface can extend a type alias, and vice versa.

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; };
  1. Implements

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을 사용한다.

profile
You only have to right once

0개의 댓글