Every Type

공부의 기록·2022년 2월 6일
0

TypeScript

목록 보기
2/2
post-thumbnail

Introduce

본 문서는 2022년 2월 6일 에 작성되었습니다.

Every Types - TypeScript Docs 를 기본으로 작성된 문서입니다.

Types

JavaScript 와 TypeScript 의 가장 큰 차이는 Type의 유무 입니다.
즉, TypeScript 에서 변수를 사용하기 전에 항상 Type을 지정 해주어야 합니다.

다음과 같은 Type 이 있습니다.

  1. Primitives Type
  2. Arrays' Type
  3. Function Parameter, Return Type
  4. Object's Type
  5. Union Type
  6. ✅ Type Aliases
  7. ✅ Interfaces

Primitives Type

JavaScript 는 범용적으로 사용되는 3가지 자료형을 가지고 있습니다.

  • string, number, boolean

TypeScript 또한 이 자료형을 그대로 사용하고 있습니다.

  • string, number, boolean

Arrays' Type

TypeScript 의 Arrays 는 ✅ 3가지 PrimitivesAny 라는 Type 을 가지고 있습니다.

  • string, number, boolean
  • any

# Primitives

동시에 2가지 방법으로 타입을 부여할 수 있습니다.

  • literal syntax
  • generics syntax
// literal syntax
const array: number[];

// generics syntax
const array: Arrays<number>;

# any

변수를 선언할 당시,
어떤 자료형의 배열을 받아들일지 모를 때 any 를 사용할 수 있습니다.

const array: any;

Function Parameter, Return Type

TypeScript 함수에서는 다음의 경우에 Type 을 정해줘야 합니다.

  1. Function Parameter Type
  2. Function Return Type
function greet(name: string): string {
  return name+"님 안녕하세요!";
}

Object's Type

JavaScritp 에서 일련의 데이터들을 하나의 집합으로 사용한 것을 배웠을 것입니다.

TypeScript 또한 이러한 객체를 사용할 수 있지만,
객체의 모든 하위 변수에 대한 Type 을 지정해주어야 합니다.
또한 객체에 선택값이 있을 경우 변수명 뒤에 ? 를 붙이면 됩니다.

function printName(obj:{ first:string, last?:string }) {
  if (obj.last != undefined) {
    console.log(obj.last.toUppserCase());
  }
}

Object Type 과 Union Type 을 결합하여,
후술할 ✅ Type Aliases 의 형태로 사용 가능합니다.

✅ Union Type

TypeScript 에ㅓ는 Union Type 이라는 새로운 타입을 만들 수 있습니다.

다음과 같은 예시가 있습니다.

  1. string 혹은 number 인 값
  2. stirng[] 혹은 string 인 값
function printValue(id: number | string) {
  console.log(id);
}
printValue(10); // 10
printValue("unchaptered"); // unchaptered

Primitives Type 과 Arrays' Type 을 같이 쓸 수도 있다...

✅ Type Aliases

TypeScript 에서는 Object Type, Union Type 을 합쳐서 선언할 수 있습니다.
이를 Type Aliases 라고 하며 다음과 같이 작성할 수 있습니다.

type Point = {
  x: number;
  y: number;
}
function printValue(target: Point) {
  console.log(target.x);
  console.log(target.y);
}
printValue({ x:100, y:100 });

아래와 같이 단일 Union Type 을 Type Aliases 형태로 쓸 수 있다.

type ID=stirng | number;

✅ Interfaces

TypeScript 의 Type Aliases 와 유사한 기능을 하는 것으로 Interfaces 가 있습니다.

interface Point {
  x: number;
  y: number;
}
function printValue(target: Point) {
  console.log(target.x);
  console.log(target.y);
}
printValue({ x:100, y:100 });

🤔 Interfaces vs Type Aliases

Type Aliases 와 Interfaces 는 다음과 같은 차이점이 있습니다.

  1. 두 Type의 상속 문법이 다릅니다.
  2. Interfaces 는 중복 선언을 통해 새 필드를 추가할 수 있으나,
    Type Aliases는 는 중복 선언이 불가능합니다.

또한 공식문서에서는 Interfaces 만의 특징을 추가로 서술하고 있었습니다.

  1. Interfaces 는 객체의 필드를 선언하는데 사용되며,
    원시자료형의 이름을 바꾸는데는 사용될 수 없습니다.
  2. Interfaces 는 에러 발생 시 정확하게 나타납니다.

🤔 Literal Types

전술한 ✅ Primitives 의 경우,
별도로 Type 을 지정하지 않아도 Literal Types 라는 방법을 사용할 수 있습니다.
JavaScript 의 변수형인 var, const, let 을 다음과 같이 작성할 수 있습니다.

// var or let
let string="unchaptered";
string; // let string: string

// const
const string="unchaptered";
string; // const string: "unchaptered"

이러한 Literal Types 을 활용하여 var,let 타입의 변수를 특정 값에 고정 할 수 있습니다.

let string:"unchaptered" = "unchaptered";
x="unchaptered"; // ok
x="hello~~"; // error

let string:"unchaptered" | "mario" | "goal";
string="unchaptered"; // ok
string="mario"; // ok
string="goal"; // ok
string="hello~~"; // error

🤔 More

TypeScript 에는 다음과 같은 자료형들이 있습니다.

  1. null, undefined
  2. Enums
  3. Less Common Primitives : bigint, symbol
profile
2022년 12월 9일 부터 노션 페이지에서 작성을 이어가고 있습니다.

0개의 댓글