본문 바로가기
Today I learned!/오늘 하루 배운 것, 기억할 것

[TS]readonly 속성, 인덱스 시그니처,intersection 타입...

by sweesweet 2023. 5. 7.

readonly 

말 그대로 읽기 전용. 해당 속성을 읽기 전용으로 지정 가능. 수정할 수 없음. 다만, 아래와 같은 예인 경우는 가능

interface Home {
  readonly resident: { name: string; age: number };
}
 
function visitForBirthday(home: Home) {
  console.log(`Happy birthday ${home.resident.name}!`);
  home.resident.age++;
}
 
function evict(home: Home) {
  home.resident = {
    name: "Victor the Evictor",
    age: 42,
  };//Error!!
  }

resident 객체 안의 속성은 업데이트가 가능하지만, home의 resident 자체는 수정이 불가능 

 

Index Signatures

interface StringArray {
  [index: number]: string;
}

가끔 타입 프로퍼티의 이름은 모르지만, 값의 형태는 알 때 사용

인덱스 시그니처를 사용 할 때, string,number,symbil,template string patterns, 유니온타입만 가능

readonly 속성을 통해 읽기 전용으로도 만들 수 있음(인덱스로 접근 시 수정x)

 

Intersection Types

표기 & / 예: Atype & Btype

다른 타입들을 합쳐 새로운 타입으로 만듦

interface Colorful {
  color: string;
}
interface Circle {
  radius: number;
}
 
type ColorfulCircle = Colorful & Circle;
 

타입 Colorfulcircle 은 color과 radius 두 속성을 모두 갖게 됨.

 

Generic Object Types

interface ddd<Type>{
  test: Type
}

let bb:ddd<string>={test:'wow'}

이런식으로 표현 가능( 이해는 했으나, 말로 설명을 못하겠음.).