readonly, 인덱스드 시그니처, 맵드 타입스

모두의희망·2023년 1월 25일
0

TypeScript

목록 보기
11/11
post-thumbnail

readonly

interface A {
   readonly a: string;
   b: string;
}
const aaaa: A = {a: 'hello', b: 'world'};
aaaa.a = '123'; //readonly때문에 a는 바뀌지 않는다 읽기전용 속성
  • 위의 코드에서 readonly라는 속성 때매 aaaa.a = '123';으로 코드를 작성 했을 때 123으로 바뀌어야 하는데 바뀌지 않는다 읽기 전용 속성
  • 속성을 실수로 바꿀 때 이를 막아 줄 수 있다.

인덱스드 시그니처

type A = {a: string, b: string, c: string, d: string};
const aaaa: A = {a: 'hello', b: 'world'};

type A = { [key: string]: number };
const aaaa: A = { a: 3, b: 5, c: 5, d: 123 };
  • 어떤 속성이든 상관 없고 값이 모두 string이였으면 좋겠다면 일일이 적어 줄 수 도 있지만 속성이 많으면 인덱스드 시그니처를 사용한다.

맵드 타입스

type B = 'Human' | 'Mammal' | 'Animal';
type A = { [key in B]: number };
const aaaa: A = { Human: 123, Mammal: 5, Animal: 7};

interface에서는 |(또는)이 안된다.

profile
개발을 진정성 있게 다가가겠습니다.

0개의 댓글