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

Suyeon·2020년 11월 10일
0

Typescript

목록 보기
3/12

Type Assertions

any 혹은 unkown 으로 선언해두고 참조할 때 타입을 assert함 (type 덮어쓰기)

// (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

하나 이상의 타입을 사용할 때 (more flexible)

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){...}
profile
Hello World.

0개의 댓글