[typescript] Type assertions, union type, literal type, alias


Type Assertions


anyまたはunbownとして宣言して参照するときのブレークスルータイプ(タイプオーバーライド)
// (1) as
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length; // (*)

// (2) angle-bracket
let someValue: unknown = "this is a string";
let strLength: number = (<string>someValue).length;  // (*)

Union Type


1つ以上のタイプを使用する場合(より柔軟)
function combine(input1: number | string, input2: number | string) {// (*)
  let result;
  
  if(typeof input1 === 'number' && typeof input2 === 'number') { // runtime type check
  	return input1 + input2;
  } else {
    return input1.toString() + input2.toString();
  }
  return result;
}

const combineAge = combine(21, 30);
const combineName = combine('Suyeon', 'Hanna');

Literal Type


It allows an exact value which a string, number, or boolean must have.
  • string/number/boolean
  • // string
    function createElement(tagName: "img"): HTMLImageElement;
    function createElement(tagName: "input"): HTMLInputElement;
    function(reslut: 'img' | 'text') {
       if(result === 'text') {
        // ...
        } else {
        // ...
        }
    }
    
    // number
    interface MapConfig {
      tileSize: 8 | 16 | 32;
    }
    
    setupMap({ tileSize: 16 });
    
    // boolean
    interface ValidationSuccess {
      isValid: true;
    };

    Alias


    Reusable custom type set.
    type pet = 'cat' | 'dog';
    type Combinable = string | number;
    
    function combine(input1: Combinable, input2: Combinable){...}