Elice SW engineer - TIL day 23

Circlewee·2022년 5월 4일
0

Elice SW 2 TIL

목록 보기
20/31

1. TypeScript

JS의 단점을 극복하기위해 나온 언어.

  • 코드의 직관성, 동적 타입의 문제, null과 undefined의 예측 불가능 등
    => 정적으로 타입을 정해두어서 버그 발견 시점을 앞당기고 코드 수정 및 리팩터링을 용이하게 할 수 있다!
/** 
 * 1을 더한 값을 돌려주는 함수
 * @param {number} value
 * @returns {number} */
function addOne(value) {
  return value + 1;
}
function addOne(value: number): number{
  return value + 1;
}

1.1 작동 방식

  • Typescript는 Javascript의 확대 집합(superset)이다. 따라서 JS로 작성된 코드는 TS코드이기도 하다.
  • tsc를 비롯한 컴파일러를 통해 작성된 코드를 JS로 변환해 빌드하는 방식이다.
  • tsc: TypeScript Compilar의 약자로 TS 전용 컴파일러를 말한다.
  • tsconfig.json: Typescript 컴파일러를 튜닝하기 위한 설정 파일이다.

1.2 Union & intersection

// union
function sayAndReturnNumberOrString(phrase: number | string) {
  console.log(`Hey, ${phrase}`);
  return phrase;
}

interface IDBConfig {
  host: string;
  port: number;
  user: string;
  password: string;
  schema?: string;
}

interface ExtraConfig {
  encrypt: boolean;
  dbName: string;
}
// intersection
// IDBConfig의 property와 ExtraConfig의 property를 합친 interface
function printDBConfig(config: IDBConfig & ExtraConfig) {
  console.log(config);
}

1.3 type alias

  • 임의의 타입을 지정한 type변수를 만들 때 사용하는 방법
type ID = string | number;
type Point = {
  x: number;
  y: number;
}

// 
function point1(p: Point): Point{
  return {x: p.x + 1, y: p.y + 1};
}
const p1: Point = {x: 2, y: 2}
console.log(point1({x: 1, y: 1}));
console.log(point1(p1));
profile
공부할 게 너무 많아요

0개의 댓글

관련 채용 정보