코드베이스를 향상시키는 5가지 TypeScript 기능

타이프스크립트의 등장은 개발자가 자바스크립트 애플리케이션을 다루는 방식을 바꿨습니다. 강력한 리팩토링 기능과 JS 코드를 작성하는 더 스마트한 방법을 제공하여 유형 안전성을 통해 코드 안정성을 제공할 뿐만 아니라 개발자 경험을 개선합니다.

이 게시물에서는 코드베이스를 향상시킬 다섯 가지 유형 스크립트 기능에 대해 이야기하고 싶습니다.

내용의 테이블


  • Nullish coalescing
  • Type guards
  • Enum object keys
  • Generic interfaces
  • Generic function parameter types

  • 1. 무효 합체

    Let's consider the following example.

    function getNumberOrDefault(value?: number) {
      return value || 22;
    }
    

    In the mentioned example, we would like to return a default value, if the provided value is undefined. However, this code has a severe pitfall — javascript treats 0 as a falsy value.

    console.log(getNumberOrDefault(10)) // Output 10
    console.log(getNumberOrDefault(0)) // Output 22
    

    Returning 22 is probably, not something we expect this function to do. Thanks to the nullish coalescing we don't need to refactor the code and add check for 0 , instead we can use a shorthand syntax with ?? .

    function getNumberOrDefaultTs(value?: number) {
        return value ?? 22;
    }
    
    console.log(getNumberOrDefault(10)) // Output 10
    console.log(getNumberOrDefault(0)) // Output 0
    

    2. 유형 가드

    Let's imagine we have two types, Truck and F1 , which extend the same interface Car . Although they share some common properties, they also possess a set of unique attributes like load and acceleration respectively.

    interface Car {
      model: string;
    }
    
    interface Truck extends Car {
      load: number;
    }
    
    interface F1 extends Car {
      acceleration: number;
    }
    
    function scanCar(car: Truck | F1) {
        ...some code
    }
    

    Also, we have a function scanCar which accepts either a Truck or a F1 and performs some type-specific actions.

    Type guard is a great way to let typescript know with which type we are currently dealing.

    function carIsTruck(car: Truck | F1): car is Truck {
      return 'load' in car;
    }
    
    function scanCar(car: Truck | F1) {
      if(carIsTruck(car)) {
            // Only truck properties will be suggested
        console.log(`Truck has a load of ${car.load}`)
      } else {
            // Only F1 properties will be suggested
        console.log(`F1 has acceleration of ${car.acceleration}`)
      }
    }
    

    Type guard is a function that returns a boolean, which is often used as part of the conditional statement, to let typescript know which type is assumed in the current if block.

    3. 개체 키 열거

    There are some cases when we want to enforce object keys being certain values only. And here is how we can achieve it using enum and Record .

    enum Size {
      M,
      L,
      XL
    }
    
    function getPlainTextSizes(): Record<Size, string> {
      return {
        [Size.M]: "medium",
        [Size.L]: "large",
        [Size.XL]: "extra large",
        10: "small", // error
        "size": "xs" // error
      }
    }
    

    Record is a generic type util, which allows defining types for key-value maps.

    4. 일반 인터페이스

    interface Item<T> {
      id: number,
      value: T,
    }
    
    interface Post {
      title: string;
    }
    
    const item1: Item<number> = { id: 1, value: 10 }
    const item2: Item<Post> = { id: 1, value: { title: "Post name" } }
    

    Generics in typescript significantly improve code reusability.

    5. 일반 함수 매개변수 유형

    interface Book {
      id: number;
      author: string;
    }
    
    interface Recipe {
      id: number;
      cookingTime: number;
    }
    
    function mapById<T extends { id: number }>(array: T[]): {[key: number]: T} {
      return array.reduce((map, item) => ({ ...map, [item.id]: item }), {})
    }
    
    const books: Book[] = [{ id: 1, author: "A" }];
    const recipies: Recipe[] = [{ id: 1, cookingTime: 10 }];
    
    mapById(books);
    mapById(recipies);
    

    It's often the case that we have util functions which require only some field from the interface. In the example above you can see a function which takes an array as input and returns values mapped by id. The only important thing is that the items of the array have an id . When you pass a parameter to the function typescript will:

    1. Infere the type of the provided parameter
    2. Check if the parameter matches specified condition (must have id of type number) So now you are save to use this helper for various interfaces.

    요약



    보시다시피 typescript는 유형 안전성을 희생하지 않고 재사용 가능하고 유연한 코드를 작성할 수 있는 많은 도구를 제공합니다.

    읽어 주셔서 감사합니다! 이 게시물은 새로운 형식의 실험입니다. 흥미롭고 도움이 되셨다면 알려주세요. 웹 개발에 대한 더 멋진 정보와 소문을 퍼뜨리는 데 도움을 주세요! 🚀

    좋은 웹페이지 즐겨찾기