본문 바로가기
TIL

[TIL] 2023.05.20 Typescript

by heereal 2023. 5. 20.

기본 타입 지정

let project: { member: string[]; days: number; started: boolean } = {
  member: ['kim', 'park'],
  days: 30,
  started: true,
};

 

Union type 

let age: string | number = 'kim';
let name: (string | number) = 100;.

let array: (number | string)[] = [1,'2',3]
let object: {data : (number | string) } = { data : '123' }
let 학교: {
  score: (number | boolean)[];
  teacher: string;
  friend: string | string[];
} = {
  score: [100, 97, 84],
  teacher: 'Phil',
  friend: 'John',
};
학교.score[4] = false;
학교.friend = ['Lee', 학교.teacher];

 

Type Narrowing 

function 내함수(x :number | string){
  if (typeof x === 'number') {
    return x + 1
  } 
  else if (typeof x === 'string') {
    return x + 1
  }
  else {
    return 0
  }
}

if문과 typeof를 사용해서 타입을 하나로 지정한다.

 

object의 요소가 선택 사항이라면

type Square = {
  color? : string,
  width : number,
}

let 네모2 :Square = { 
  width : 100 
}

객체의 타입에 물음표 연산자를 추가하면 undefined라는 타입도 가질 수 있다는 뜻이 된다.

 

Type Extend

type PositionX = { x: number };
type PositionY = { y: number };

// 두 가지 방법 모두 가능
type XandY = PositionX & PositionY
type XandY = PositionX & { y: number }

let 좌표 :XandY = { x : 1, y : 2 }

 


회고

수정 전 / 수정 후

강의 듣다가 재미 없어서 딴짓하다가.. 블로그 게시물 하단에 관련글 이미지랑 텍스트 겹치던 문제 드디어 해결했다 ㅋㅋ 

 

이것저것 직접 써 보면서 공부하기📝

예전부터 들어야지 생각했던 코딩애플 typescript 강의를 들었다. 강의 초반이라 기초 개념 관련된 내용이었긴 한데 기초를 탄탄하게 다시 쌓는 느낌이라 좋았다. typescript 정복하기 화이팅~~

 

 

댓글