JavaScript

[TypeScript] 인터페이스 (Optional, readonly, extends)

코딩하는 Jay 2021. 11. 10. 23:22
반응형

TypeScript

 자바스크립트에서 데이터를 그룹화하고 전달하는 방법으로 Object를 사용합니다. 타입스크립트에서는 Object Type을 통해 Object를 표현합니다. Object Type에 이름을 지정하기 위해 인터페이스를 사용합니다.

interface Person {
  name: string;
  age: number;
}
 
function greet(person: Person) {
  return "Hello " + person.name;
}

 위 코드에서 greet 함수의 매개변수로 person 변수를 받고 있습니다. person 변수의 타입은 Person으로 interface로 선언되어 있는 것을 확인할 수 있습니다. Person은 name이라는 string과 age라는 number 변수를 가진 Object로 선언되어 있습니다.

 

Optional 속성

 인터페이스의 속성을 Optional로 지정할 수 있습니다. Optional로 지정하면 해당 속성을 제공할 지 말지를 결정할 수 있습니다. 특정 속성을 Optional로 지정하기 위해서는 속성명 옆에 물음표(?)를 넣으면 됩니다.

interface PaintOptions {
  shape: Shape;
  xPos?: number;
  yPos?: number;
}
 
function paintShape(opts: PaintOptions) {
  // ...
}
 
const shape = getShape();
paintShape({ shape });
paintShape({ shape, xPos: 100 });
paintShape({ shape, yPos: 100 });
paintShape({ shape, xPos: 100, yPos: 100 });

 위 코드에서 PaintOptions 인터페이스가 선언되어 있습니다. PaintOptions 인터페이스는 xPos, yPos를 Optional로 지정했습니다. Optional로 지정된 xPos, xPos 값은 모두 없을 수도, 하나만 있을 수도 그리고 모두 있을 수도 있습니다. 

 

Readonly 속성

 속성을 읽기 전용으로 만들기 위해서는 readonly 키워드를 사용하면 됩니다.

interface SomeType {
  readonly prop: string;
}
 
function doSomething(obj: SomeType) {
  // We can read from 'obj.prop'.
  console.log(`prop has the value '${obj.prop}'.`);
 
  // But we can't re-assign it.
  obj.prop = "hello";	// Cannot assign to 'prop' because it is a read-only property.
}

 위 코드에는 SomeType이라는 인터페이스가 선언되어 있습니다. SomeType 인터페이스에는 prop이라는 속성이 있는데, 이 속성 이름 앞에는 readonly 키워드가 사용된 것을 확인할 수 있습니다. 즉, SomeType의 prop 속성은 읽기전용입니다. doSomething 함수 내부에서 obj.prop = "hello" 구문을 이용해 prop 속성에 문자열 "hello"를 대입하려고 시도하고 있습니다. 이때 TypeScript는 Cannot assign to 'prop' because it is a read-only property. 이라는 에러 메시지를 표시하는 것을 확인할 수 있습니다. 

 

인터페이스 확장

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

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

 위 코드에는 두 개의 인터페이스가 선언되어 있습니다. AddressWithUnit은 이름에서도 알 수 있듯이 BasicAddress에 unit 속성이 하나 추가되어 있는 형태를 갖고 있습니다. 이러한 경우, extends 키워드를 사용해 인터페이스를 확장할 수 있습니다.

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

 위 코드와 같이 AddressWithUnit 인터페이스는 BasicAddress의 속성을 상속받아 사용한다는 의미로 extends 키워드를 사용하여 확장 할 수 있습니다.  만약 두개의 인터페이스를 확장하는 경우, 쉼표로 구분하여 확장이 가능합니다.

 

참고:

https://www.typescriptlang.org/docs/handbook/2/objects.html

 

Documentation - Object Types

How TypeScript describes the shapes of JavaScript objects.

www.typescriptlang.org

 

반응형