ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Array
    TypeScript 2023. 6. 6. 20:40

    타입스크립트에서 Array의 개념 및 문법에 대해 정리하였습니다.

     

     


    < Array Type Annotations >

    To put type annotation for array types

     

    • method 1: put [ ] after the element type
    let names: string[] = ['Danny', 'Samantha'];

     

    • method 2: use Array<T> syntax; T stands for the type.
    let names: Array<string> = ['Danny', 'Samantha'];

     

    Example)

    let names: string[] = [1,2,3]; // Type Error!
    
    let names: string[] = ['Damien'];
    names.push(666) // Type Error!

     

     


    Multi-dimensional Arrays >

    To put type annotation for Multi-dimensional Arrays: arrays of arrays of some type

     

    Example)

    let arr: string[][] = [['str1', 'str2'], ['more', 'strings']];
    
    let bestNumbers: number[] = [7,77,4];
    let numbersMulti: number[][][] = [ [[1],[2,3]], [[7],bestNumbers] ];

     

     


    Tuples >

    JavaScript arrays are flexible and can have elements of different types. With TypeScript, we can also define arrays with a fixed sequence of types

    In TypeScript, when an array is typed with elements of specific types, it's called a tuple.

     

    • Tuple types specify both the lengths and the orders of compatible tuples,
      will cause an error if either of these conditions are not met

     

    Example1)

    let ourTuple: [string, number, string, boolean] = ['Is', 7 , 'our favorite number?' , false]; 
    
    let numbersTuple: [number, number, number] = [1,2,3,4]; // Type Error! numbersTuple should only have three elements.
    let mixedTuple: [number, string, boolean] = ['hi', 3, true] // Type Error! The first elements should be a number, the second a string, and the third a boolean.

     

    Example2)

    let tup: [string, string] = ['hi', 'bye'];
    let arr: string[] = ['there','there'];
    tup = ['there', 'there']; // No Errors.
    tup = arr; // Type Error! An array cannot be assigned to a tuple.

    : Tuple acts like array. But despite their similarities, tuples and arrays do not have compatible types within TypeScript.

     

     


    Array Type Inference >

    TypeScript can infer variable types from initial values and return statements. Even still, we may not know exactly what type inference to expect when dealing with arrays.

     

    Example1)

    let examAnswers= [true, false, false];
    
    examAnswers[3] = true; // No type error

    : examAnswers's type is boolean[] (not a [boolean, boolean, boolean] )

     

    Example2)

    let tupleOfExamAnswers: [boolean, boolean, boolean] = [true, false, false];
    tupleOfExamAnswers[3] = true; // Type error! The tuple only has 3 elements.

    : examAnswers's type is array, tupleOfExamAnswers's type is tuple

     

    • The takeaway here is that type inference returns arrays. When we want tuples, we need to use explicit type annotations.

     

     


    Rest Parameters >

    To adding types to rest parameters

     

    Example)

    function smush(firstString, ...otherStrings){
      let output = firstString;
      for(let i = 0; i < otherStrings.length; i++){
        output = output.concat(otherStrings[i]);
      }
      return output;
    }
    
    smush('a','h','h','H','H','H','!','!'); // Returns: 'ahhHHH!!'.

    : it's not type safe. because a mistake like smush(1,2,3) would cause an error.

     

    function smush(firstString, ...otherStrings: string[]){
      /*rest of function*/
    }

    With this change, TypeScript will treat otherStrings as an array of string.

     

     


    Spread Syntax >

    Tuples pair beautifully with JavaScript's spread syntax. This is most useful for function calls that use lots of arguments.

     

    Example)

    function gpsNavigate(startLatitudeDegrees:number, startLatitudeMinutes:number, startNorthOrSouth:string, startLongitudeDegrees: number, startLongitudeMinutes: number, startEastOrWest:string, endLatitudeDegrees:number, endLatitudeMinutes:number , endNorthOrSouth:string, endLongitudeDegrees: number, endLongitudeMinutes: number,  endEastOrWest:string) {
      /* navigation subroutine here */
    }
    
    // bad
    gpsNavigate(40, 43.2, 'N', 73, 59.8, 'W', 25, 0, 'N', 71, 0, 'W')
    
    // good
    let codecademyCoordinates: [number, number, string, number, number, string] = [40, 43.2, 'N', 73, 59.8, 'W'];
    let bermudaTCoordinates: [number, number, string, number, number, string] = [25, 0 , 'N' , 71, 0, 'W'];
    
    gpsNavigate(...codecademyCoordinates, ...bermudaTCoordinates);
    // And by the way, this makes the return trip really convenient to compute too:
    gpsNavigate(...bermudaTCoordinates, ...codecademyCoordinates);
    // If there is a return trip . . .

     

     

     

    'TypeScript' 카테고리의 다른 글

    Type Narrowing  (0) 2023.07.24
    Union Types  (0) 2023.07.07
    Custom Types  (0) 2023.06.19
    Functions  (0) 2023.05.25
    Types  (0) 2023.05.04

    댓글

Designed by Tistory.