(*ᴗ͈ˬᴗ͈)ꕤ*.゚ 2022. 6. 29. 14:02

0. 기본

type Age = number;
type Name = string;
type Player = {
  name: Name
  age?: Age
}

const playerMaker = (name: string): Player => ({name})
const nico = playerMaker("nico")
nico.age = 12
// 항상 정해져있는 갯수의 요소를 가져오는 배열을 생성해야할 때 유용
const player: [string, number, boolean] = ["nico", 1, true];

player[0] = 1; // not allowed ([0]: string)

const player: readonly [string, number, boolean] = ["nico", 1, true];

player[0] = "h1"; // not allowed(readonly);

1. unknown

let a : unknown;

let b = a + 1 // 불가능; a가 unknown이기 때문

// 아래의 방법으로 수행
if(typeof a == 'number'){
  let b = a + 1;
}

if(typeof a == 'string'){
  let b = a.toUpperCase();
}



2. void: return하지 않는 함수

// void 예시
function hello(){
  console.log('x')
}

// 아래와 같은 방식으로는 쓰지 않음(타입스크립트가 인식하기 때문)
function hello:void(){
  console.log('x')
}

// void는 return을 하지않기 때문에 아래와 같은 방식은 에러가 남
const a = hello();
a.toUpperCase(); // -> Err

 

3. never: 함수가 절대절대 return 하지 않음

// 아래의 함수는 절대 리턴하지 않음
function hello():never{
  return "X";
}

// 아래의 함수 가능
function hello():never{
  throw new Error("xxx");
}

 

function hello(name: string | number){
  if(typeof name === "string"){
   name // string
  } else if (typeof name === "number"){
   name // number
  } else {
    name //<- never
  }
}