Bin's Blog

오늘의 TypeScript 본문

TypeScript

오늘의 TypeScript

hotIce 2023. 5. 9. 16:21
728x90
  • type Alias
//영어 대문자 국룰
type AnimalType = {name : string, age: number}

let 동물 : AnimalType = { name : "kim", age : 20}


// const 변수는 등호로 재할당만 막는 역할이다
// const로 담은 Object 수정은 자유롭게 가능
const 출생지역 = { region : "seoul" };
출생지역.region = "busan"

//readonly 쓰면 object 자료 수정도 막을 수 있다.
// 수정하면 에러가 뜬다.
// object 속성 안에도 ? 사용가능
type Girlfriend = {
  readonly name: string
  age? : number
}

// 타입스크립트 에러는 에디터 & 터미널에서만 존재함
// 실제 Js코드는 문제없이 돌아가
const 여친 :Girlfriend = {
  name : "엠버",
  age : 21
}


type Name = string;
type Age = number;
//type 변수 union type으로 합치기 가능
type Person = Name | Age;

// 연산자로 object 타입 extend
type PositionX = { x : number };
type PositionY = { y : number };

// {x: number, y: number}
type NewType = PositionX & PositionY

let position :NewType = { x: 10, y : 20 }
  • object 타입을 정의한 type alias 두 개를 & 기호로 합칠 때 중복된 속성이 있으면 어떻게 될까?
//이름은 같은데 형태가 다른 경우
type A = {
  prop: string;
};

type B = {
  prop: number;
};

type C = A & B; // Error

// 이름도 같고 형태도 같은 경우
type A = {
  prop: string;
};

type B = {
  prop: string;
};

type C = A & B; // No error, C is { prop: string }
728x90

'TypeScript' 카테고리의 다른 글

오늘의 TypeScript  (0) 2023.07.17
오늘의 TypeScript  (0) 2023.07.16
오늘의 TypeScript  (0) 2023.05.08
오늘의 TypeScript  (0) 2023.05.05
오늘의 TypeScript  (0) 2023.05.04