[ TypeScript ] TypeScript Handbook : Object Types

·2023년 8월 8일
0

TypeScript

목록 보기
3/3
post-thumbnail

프로퍼티 수정자

readonly 프로퍼티

TypeScript에서 프로퍼티는 readonly로 표시될 수도 있다. 런타임 시 동작은 변경되지 않지만, readonly로 표시된 속성은 타입 검사 중에 쓸 수 없다.

interface SomeType {
  readonly prop: string;
}

function doSomething(obj: SomeType) {
  // 'obj.prop'을 읽을 수 있다.
  console.log(`prop has the value '${obj.prop}'.`);
  
  // 하지만 재할당할 수는 없다.
  obj.prop = "hello";
  // Cannot assign to 'prop' because it is a read-only property.
}

index signature

가끔 타입 프로퍼티의 이름을 미리 모두 알지는 못하지만, 값의 모양은 알 수 있는 경우가 있다.
이런 경우 index signature를 사용하여 가능한 값의 타입을 설명할 수 있다.

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

const myArray: StringArray = getStringArray();
const secondItem = myArray[1];

string, number, symbol, 템플릿 string 패턴, 유니온 타입에서만 index signature를 사용할 수 있다.

타입 확장

extends를 사용하면 다른 이름을 가진 타입을 효과적으로 복사하고, 원하는 새 구성원을 추가할 수 있다. 이는 타입을 선언하는 양을 줄이고 동일한 속성의 여러 다른 선언이 관련되어 있을 수 있음을 알리는데 유용하다.

interface BasicAddress {
  name?: string;
  street: string;
  city: string;
  country: string;
  postalCode: string;
}
 
interface AddressWithUnit extends BasicAddress {
  unit: string;
}

Intersection Types

interface는 다른 타입들로부터 새로운 타입들을 확장할 수 있게 해준다. TypeScript는 기존의 객체 타입들을 결합하는 데 주로 사용되는 Intersection Types라는 또 다른 구성 요소를 제공한다.
Intersection Types는 & 연산자를 사용한다.

interface Colorful {
  color: string;
}
interface Circle {
  radius: number;
}
 
type ColorfulCircle = Colorful & Circle;
profile
개발을 개발새발 열심히➰🐶

0개의 댓글