ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Union Types
    TypeScript 2023. 7. 7. 23:54

    타입스크립트의 Union Types에 대해 정리하였습니다.

     

     


    < Defining Unions >

    Unions allow us to define multiple allowed type members by separating each type member with a vertical line character |

     

     

    Example)

    let ID: string | number;
     
    // number
    ID = 1;
     
    // or string
    ID = '001';
     
    console.log(`The ID is ${ID}.`);

    : Union Types is more flexible than a single primitive type, but much more specific than the any type.

     

     


    < Type Narrowing >

    we may want to perform different logic in the function’s body that does one thing for strings and another for numbers.

    Type narrowing is when TypeScript can figure out what type a variable can be at a given point in our code.

     

    Example)

    function getMarginLeft(margin: string | number) {
      // margin may be a string or number here
     
      if (typeof margin === 'string') {
        // margin must be a string here
        return margin.toLowerCase();
      } else {
        // margin must be a number here
    }

     

     


    < Inferred Union Return Types >

    TypeScript can infer types in many cases so that we don't have to manually write them.

     

    Example)

    function getBook() {
      try {
        return getBookFromServer();
      } catch (error) {
        return `Something went wrong: ${error}`;
      }
    }

    : TypeScript inferes the return type a the union Book | string.

     

     


    < Unions and Arrays >

    Unions are even more powerful when used in combination with arrays.

     

    • To create a union that supports multiple types for an array's values, wrap the union in parentheses ( ), then use array notation [ ]

     

    Example)

    const dateNumber = new Date().getTime(); // returns a number
    const dateString = new Date().toString(); // returns a string
     
    const timesList: (string | number)[] = [dateNumber, dateString];

     

     


    < Common Key Value Pairs >

    When we put type members in a union, TypeScript will only allows us to use the common methods and properties that all members of the union share.
    : Any properties or methods that are not shared by all of the union's members won't be allowed and will produce a TypeScript ereror.

     

    Example)

    const batteryStatus: boolean | number = false;
     
    batteryStatus.toString(); // No TypeScript error
    batteryStatus.toFixed(2); // TypeScript error

    : boolean and number both share .toString(), but don't share .toFixed()

     

    type Goose = { 
      isPettable: boolean; 
      hasFeathers: boolean;
      canThwartAPicnic: boolean;
    }
     
    type Moose = {
      isPettable: boolean; 
      hasHoofs: boolean;
    }
     
    const pettingZooAnimal: Goose | Moose = { isPettable: true };
     
    console.log(pettingZooAnimal.isPettable); // No TypeScript error
    console.log(pettingZooAnimal.hasHoofs); // TypeScript error

    : Since .hasHoofs is only a property on Moose, we cannot call that method on pettingZooAnimal.

     

     


    Unions with Literal Types >

    We can use literal types with TypeScript with TypeScript unions. Literal type unions are useful when we want to create distinct states within a program.

     

    Example)

    type Color = 'green' | 'yellow' | 'red';
     
    function changeLight(color: Color) {
      // ...
    }

     

     

     

     

     

     

    'TypeScript' 카테고리의 다른 글

    Advanced Object Types  (0) 2023.08.09
    Type Narrowing  (0) 2023.07.24
    Custom Types  (0) 2023.06.19
    Array  (0) 2023.06.06
    Functions  (0) 2023.05.25

    댓글

Designed by Tistory.