혼자 적어보는 노트

[TypeScript] 기본 타입 / 타입 별칭 / 유니온 타입 / 인터섹션타입 본문

Typescript

[TypeScript] 기본 타입 / 타입 별칭 / 유니온 타입 / 인터섹션타입

jinist 2022. 5. 19. 17:17

기본 타입(타입주석)

  const num: number = 3;

  const str: string = "하이";

  const boal: boolean = false;
  
  let age: number | undefined;

  let person: string | null;

  function find():number | undefined{
    return undefined;
  }
  
  let name:'Jay' = 'Jay'; // 값으로 지정할 수도 있다.

  // 가능하면 쓰지 말기 3종
  let empty: null 

  let notSure: unknown = 0;

  let anything: any = 0;

  // object = {} = []
  // 이런 식으로 쓰지 말고 object는 정의해서 쓰자
  let obj: object;

 

함수

  // 함수에서 아무 값도 리턴하지 않을 때
  function print():void {
    console.log();
    return;
  }

  // never 절대 리턴할 수 없다. 에러나 while문
  function throwError(massage: string):never {
    throw new Error("error");
  }

 

 

  // Optional
  function printName(firstName: string, lastName?:string){
    console.log(firstName, lastName);
  }

  printName('Jay', 'Jon'); // Jay Jon
  printName('Jay'); // Jay undefined
  printName('Jay', undefined); // Jay undefined
  
  
  // Default parameter
  function printMessage(message: string = 'default'){
    console.log(message);
  }
  
  // Rest parameter

  function addNumbers(...numbers: number[]){
    const sum = numbers.reduce((acc, v)=> acc+v);
    console.log(sum);
  }

  addNumbers(1,2,3) // 6

 

Array

  const fruits: string[] = ['banana', 'apple'];
  const numbers: Array<number> = [1, 2, 3];

 

Tuple

배열의 길이가 고정되고 요소의 타입이 지정되어 있는 형식

let arr: [string, number] = ['Jay', 10];

 

readonly

  function readFruits(fruits: readonly string[]){
    fruits[1] = "orange"; // 안됨
  }

readonly에서는 Array<number>와 같은 제네릭 형태는 허용되지 않는다.

 

 

Type Aliases

특정 타입이나 인터페이스를 정의할 수 있다.

  // Type Aliases
  // 타입을 정의할 수 있다.
  type Text = string;
  const name: Text = "Jay";

  type Num = number;
  const age: Num = 18;

  // Object Type 정의
  type Student = {
    name: string;
    age: number;
  };

  const jay: Student = {
    name: 'jay',
    age: 20
  };

  // String Literal Types
  // 값을 타입으로 정의하기

  type Name = 'name';
  const name:Name = 'name';

정의한 타입에 대해 에디터 상에서 확인을 할 수 있다.

 

Union Type

OR 연산자와 같이 A이거나 B라는 의미

  type Success = {
    response: 'true';
    data: {
      massage: string;
    }
  };

  type Fail = {
    response: 'false';
    error: string;
  };

  type Result = Success | Fail

  function getData(result: Result){
    if(result.response === 'true'){
      console.log(result.data.massage);
    } else {
      console.log(result.error);
    }
  }

  getData({
    response: 'false',
    error: '데이터가 너무 많음'
  })

저번 영화검색기를 만들 때 response값으로 데이터가 제대로 들어왔는지

확인하는 로직이 있었어서 생각하며 작성해봤는데 이렇게 작성해볼 수도 있을 듯 하다.

 

Intersection Type

& 와 같은 개념으로 여러 타입을 만족하는 하나의 타입을 의미

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

  type Info = {
    address: string;
  }

  function userInfo(user: User & Info){
    console.log(user);
  }

  userInfo({
    name: 'jay',
    age: 20,
    address: "Uijeongbu"
  })

 

Comments