ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Custom Types
    TypeScript 2023. 6. 19. 18:08

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

     

     


    < Introduction >

    TypeScript can also be used to create custom types, rather than being limited to pre-defined types.

    Pre-defined types are like ingredients: they can be used on their own. Sometimes you just need a simple 
    string and sometimes you just want to eat a pickle! However, pre-defined types can also be combined into custom types. Custom types are like fully assembled meals (pickles, as well as cheese, bread, and burger patties).

     

     


    < Enums >

    Use enums when we'd like to enumerate all the possible values that a variable could have.
    to limit the possible values of a variable.

    An enum type is either assigned a numeric or string value.

     

    Example)

    enum Direction {
      North,
      South,
      East,
      West
    }
    
    let whichWayToArcticOcean: Direction;
    whichWayToArcticOcean = Direction.North; // No type error.
    whichWayToArcticOcean = Direction.Southeast; // Type error: Southeast is not a valid value for the Direction enum.
    whichWayToArcticOcean = West; // Wrong syntax, we must use Direction.West instead.

     

     


    < Object Types >

    TypeScript’s object types are extremely useful, as they allow us extremely fine-level control over variable types in our programs. They’re also the most common custom types, so we’ll have to understand them if we want to read other people’s programs.

     

    Example)

    let aPerson: {name: string, age: number};
    
    aPerson = {name: 'Aisle Nevertell', age: "wouldn't you like to know"}; // Type error: age property has the wrong type.
    aPerson = {name: 'Kushim', yearsOld: 5000}; // Type error: no age property. 
    aPerson = {name: 'User McCodecad', age: 22}; // Valid code.
    let aCompany: {
      companyName: string, 
      boss: {name: string, age: number}, 
      employees: {name: string, age: number}[], 
      employeeOfTheMonth: {name: string, age: number},  
      moneyEarned: number
    };

    TypeScript places no restrictions on the types of an object’s properties. They can be enums, arrays, and even other object types!

     

     


    < Type Aliases >

    To customize the types in our programs.

    Type aliases are truly useful for referring to complicated types that need to be repeated.

     

    - format :

    type <alias name> = <type>

     

    Example)

    type MyString = string;
    let myVar: MyString = 'Hi'; // Valid code.
    // bad
    let aCompany: { 
      companyName: string, 
      boss: { name: string, age: number }, 
      employees: { name: string, age: number }[], 
      employeeOfTheMonth: { name: string, age: number },  
      moneyEarned: number
    };
    
    // good
    type Person = { name: string, age: number };
    let aCompany: {
      companyName: string, 
      boss: Person, 
      employees: Person[], 
      employeeOfTheMonth: Person,  
      moneyEarned: number
    };

     

     


    Function Types >

    We can specify the argument types and return type of a function using function types.

     

    Example1)

    type StringsToNumberFunction = (arg0: string, arg1: string) => number;
    
    let myFunc: StringsToNumberFunction;
    myFunc = function(firstName: string, lastName: string) {
      return firstName.length + lastName.length;
    };
     
    myFunc = function(whatever: string, blah: string) {
      return whatever.length - blah.length;
    };
    // Neither of these assignments results in a type error.

     

    Example2)

    type StringToNumberFunction = (string)=>number; // NO
    type StringToNumberFunction = arg: string=>number; // NO NO NO NO

    : We must never be tempted to omit the parameter names or the parentheses around the parameters in a function type anontation, even if there is only one parameter.

     

     


    Generic Types >

    To create collections of types that share certain formal similarities.

    These collections are parametrized(< >) by one or more type variables.

    example: Array<string> is an array of strings.

     

    Example)

    type Family<T> = {
      parents: [T, T], mate: T, children: T[]
    };
    
    let aStringFamily: Family<string> = {
      parents: ['stern string', 'nice string'],
      mate: 'string next door', 
      children: ['stringy', 'stringo', 'stringina', 'stringolio']
    };

    Generics give us the power to define our own collections of object types.

    Writing   is just a convention. We could just as easily use  S  or  GenericType .

     

     


    Generic Functions >

    To create collections of typed functions.

     

    Example)

    // javascript
    function getFilledArray(value, n) {
      return Array(n).fill(value);
    }
    
    // typescript using generic functin: we can specify the return type in array
    function getFilledArray<T>(value: T, n: number): T[] {
      return Array(n).fill(value);
    }

    : the  T  in function  functionName<T>  allows us to use  T  within the type annotation as a type placeholder.

     

    function getFilledArray<T>(value: T, n: number): T[] {
      return Array(n).fill(value);
    }
    
    let stringArray: string[];
    let numberArray: number[];
    let personArray: {name: string, age: number}[];
    let coordinateArray: [number, number][];
    
    // Write your code below:
    stringArray = getFilledArray<string>('hi', 6);
    numberArray = getFilledArray<number>(9, 6);
    personArray = getFilledArray<{name: string, age: number}>({name: 'J. Dean', age: 24}, 6);
    coordinateArray = getFilledArray<[number, number]>([3, 4], 6);

     

     

     

    'TypeScript' 카테고리의 다른 글

    Type Narrowing  (0) 2023.07.24
    Union Types  (0) 2023.07.07
    Array  (0) 2023.06.06
    Functions  (0) 2023.05.25
    Types  (0) 2023.05.04

    댓글

Designed by Tistory.