[TypeScript] Get started!

승연·2022년 5월 9일

TypeScript

목록 보기
1/1
post-thumbnail

타입스크립트를 시작해보자!

이 글은 TypeScript for JavaScript Programmers를 요약한 글입니다.

Defining Types

interface로 객체의 type을 명시해준다.

interface User {
  name: string;
  id: number;
}

// TypeName after a variable declaration
const user: User = { 
  name: "Hayes",
  id: 0,
}

JS가 class와 OOP를 지원하기 때문에, TS도 동일!

interface User {
  name: string;
  id: number;
}

class UserAccount {
  name: string;
  id: number;

  constructor(name: string, id: number) {
    this.name = name;
    this.id = id;
  }
}

const user: User = new UserAccount("Murphy", 1);

interface를 함수의 parameter나 return값의 type 명시에도 사용할 수 있다.

function getAdminUser(): User {
  //...
}

function deleteUser(user: User) {
  // ...
}

type종류

  • boolean, bigint, null, number, string, symbol, and undefined (JS와 동일)
  • any : allow anything

    In many cases, this is too permissive. Using the any type, it's easy to write code that is type-correct, but problematic at runtime. We don't get a lot of protection from TypeScript if we're opting to use any.

  • unknown
  • never
  • void : undefined를 리턴하거나 리턴값이 없는 함수

unknownnever는 따로 다루겠습니다,,
https://mariusschulz.com/blog/the-unknown-type-in-typescript#the-any-type

Interfaces and Types

타입을 지정할 때는 interfacetype 두 가지 방식이 있는데, interface 권장.

WHY?

error message가 더 친절하다

// 1. type
type BirdType = {
  wings: 2;
};
type Owl = { nocturnal: true } & BirdType;
let owl: Owl = { wings: 2, nocturnal: true };
// 2. interface
interface BirdInterface {
  wings: 2;
}
interface Chicken extends BirdInterface {
  colourful: false;
  flies: false;
}
let chicken: Chicken = { wings: 2, colourful: false, flies: false };
1. type2. interface
chicken = owl;owl = chicken;
Type 'Owl' is missing the following properties from type 'Chicken': colourful, fliesType 'Chicken' is not assignable to type 'Owl'. Property 'nocturnal' is missing in type 'Chicken' but required in type '{ nocturnal: true; }'.

차이점

interface는 두 번째 선언으로 확장시킬 수 있지만, type은 그렇지 않다.

interfaces are open and type aliases are closed. This means you can extend an interface by declaring it a second time.

// interface
interface Kitten {
  purrs: boolean;
}

interface Kitten {
  colour: string;
}
// type
type Puppy = {
  color: string; // error: Duplicate identifier 'Puppy'.
};

type Puppy = {
  toys: number; // error: Duplicate identifier 'Puppy'.
};

Composing Types

Unions

popular use-case: string/number literal types와 결합하여 사용

type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type PositiveOddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;

이렇게 사용하면 오타를 잡아낼 때도 좋을 듯 하다!

function printText(s: string, alignment: "left" | "right" | "center") {
  // ...
}
printText("Hello, world", "left");
printText("G'day, mate", "centre"); // Argument of type '"centre"' is not assignable to parameter of type '"left" | "right" | "center"'.

또는 다른 type을 동시에 선언할 수도 있음

function getLength(obj: string | string[]) {
  return obj.length;
}

Generics

Generics은 변수에 타입을 제공

보통 Array에 사용 : Array 내부 값들의 타입을 지정

type StringArray = Array<string>;
type NumberArray = Array<number>;
type ObjectWithNameArray = Array<{ name: string }>;

Type parameter를 통해 사용하는 쪽에서 타입을 결정할 수 있음

// 출처: https://www.youtube.com/watch?v=pReXmUBjU3E&list=PLZKTXPmaJk8KhKQ_BILr1JKCJbR0EGlx0&index=7
function getSize<T>(arr: T[]): number {
  return arr.length;
}

const arr1 = [1,2,3];
getSize<number>(arra1); // 3

const arr2 = ["a", "b", "c"];
getSize<string>(arr2); //3
interface Mobile<T> {
  name: string;
  price: number;
  option: T;
}

const m1: Mobile<object> = {
  name: "s21",
  price: 1000,
  option: {
    color: "red",
    coupon: false,
  },
};

0개의 댓글