extends
, implements
를 사용할 수 있지만 타입 정의 내에 union
이 사용된 경우 사용할 수 없다. type TypeA = {
str: string;
};
// union type으로 정의된 경우 extends 나 implements 와 사용할 수 없다.
type TypeB = TypeA | {
num: number;
};
class Person implements TypeB {} /* 오류 */
// A class can only implement an object type or intersection of object types with statically known members.
interface Person extends TypeB {} /* 오류 */
// An interface can only extend an object type or intersection of object types with statically known members.
type Name = string;
type myAction =
| { type: "COUNT"; count: number }
| { type: "EAT"; food: string }
| { type: "READ"; book: string };
TypeScript 팀은 개방-폐쇄 원칙(소프트웨어 개체(클래스, 모듈, 함수 등등)는 확장에 대해 열려 있어야 하고, 수정에 대해서는 닫혀 있어야 한다)에 따라 확장에 열려있는 JavaScript 객체의 동작 방식과 비슷하게 연결하도록
Interface
를 설계했습니다.참고:
리액트의 state 타입 지정을 할 때 예시에서 type 키워드를 사용하는 것을 보고 interface와의 확실히 하고 싶어 찾아보았다. state 타입 지정은 일반적으로 인터페이스를 사용하고, union 혹은 tuple 타입을 써야하는 경우 type 을 사용한다. useReducer에서 action 정의는 type을 사용해야 하는 경우이다. 내가 느끼는 가장 큰 차이점은 declaration merging이며 public api의 경우 interface를 사용하는 것이 맞고, 그 외에는 팀 내 공통 컨벤션을 정하여 사용하면 될 듯 하다.