남과 같이 해선 남 이상이 될 수 없다.

TypeScript

2021/06/19 TypeScript

맨동 2021. 6. 19. 22:42
728x90

TypeScript interface

기존에 자바스크립트에는 인터페이스라는 개념이 없었습니다. 하지만 타입스크립트를 이용해 인터페이스를 사용할 수 있게 됐습니다. 인터페이스란 간단하게 어떠한 두개의 시스템 사이에 상호작용할 수 있게 해주는 조건, 규약 같은 것입니다.

컴파일 타임에만 사용되고 js 파일에는 나타나지 않는다!

 

//TS
function hello1(person: {name:string; age:number}):void {
  console.log(`hi im ${person.name}, ${person.age}years`);
}

const p1 : {name:string; age:number}={
  name:"Dongit",
  age:25
};

hello1(p1);

기존 타입스크립트의 코드가 위와 같을 때, 정의할 사람의 수가 많아지면 코드가 지저분해질겁니다.

하지만 타입스크립트의 interface 를 사용하면 더욱 가독성이 좋은 코드로 만들 수 있습니다.

 

//TS
interface Person1 {
  name: string;
  age: number;
}

function hello1(person: Person1): void {
  console.log(`hi im ${person.name}, ${person.age}years`);
}

const p1: Person1 = {
  name: "Mark",
  age: 25
};

hello1(p1);

 

선택적 프로퍼티

의도적으로 객체에 프로퍼티가 있어도 되고 없어도 되는 경우에는 선택적 프로퍼티를 사용합니다.

프로퍼티 이름의 끝에 ? 를 넣어주면 됩니다.

 

//TS
interface Person2 {
  name: string;
  age?: number;
}

function hello2(person: Person2): void {
  console.log(`hi im ${person.name}`);
}

const p1: Person2 = {
  name: "Mark",
};

hello2(p1);

 

프로퍼티명을 미리 정하지 않고 어떤 이름의 프로퍼티가 와도 상관이 없게 만들려면 

Indexable 타입 을 사용하시면 됩니다.

[ key : KeyType ] : PropertyType의 형태로 사용이 가능합니다.

 

//TS
interface Person3 {
  name: string;
  age?: number;
  [index: string]: any;
}

function hello3(person: Person3): void {
  console.log(`hi im ${person.name}`);
}

const p3: Person3 = {
  name: "Mark",
  // age: 25
};

const p4: Person3 = {
  name: "Anna",
  systers: ["Sung", "Chan"],
}

const p5: Person3 = {
  name: "Baby",
  fater: p3,
  mother: p4,
}

 

Interface 안에서 Function을 정의하는 법

//TS
interface Person4 {
  name: string;
  age: number;
  hello(): void;
}

const p5: Person4 = {
  name: 'Dongit',
  age: 25,
  hello(): void {
    console.log(`안녕하세요 ${this.name} 입니다.`);
  },
};

// 화살표 함수에서 this는 golobalThis 를 가르키기 때문에 에러
// const p6: Person4 = {
//   name: 'Dongit',
//   age: 25,
//   hello:():void => {
//   console.log(`안녕하세요 ${this.name} 입니다.`);
// }
// }

p5.hello();

 

extends interface

인터페이스의 결합이 가능합니다.

//TS
interface IPerson1 {
  name: string;
  age?: number;
}
interface IKorean extends IPerson1 {
  city: string;
}

const k: IKorean = {
  name: 'Dongit',
  city: "서울"
}

 

Readonly Interface Properties

Typescript는 readonly 키워드를 사용할 수 있습니다.

readonly가 선언된 클래스 프로퍼티는 선언 시 또는 생성자 내부에서만 값을 할당할 수 있습니다.

그 외의 경우에는 값을 할당할 수 없고 오직 읽기만 가능한 상태가 됩니다.

이를 이용하여 상수의 선언등에 사용됩니다.

 

//TS
interface Person5 {
  name: string;
  age?: number;
  readonly gender: string;
}

const p5: Person5 = {
  name: 'Dongit',
  gender:'male',
};

//Error
//p5.gender = "female";

 

type alias(타입별칭) vs interface(인터페이스)

 

function

//type alias
type EatType = (food:string) => void;

//interface
interface IEat {
  (food:string): void;
}

 

array

//type alias
type Person = string[];

//interface
interface IPerson {
  [index:number]: string;
}

 

Declaration Merging

 

Interface는 같은 이름으로 여러 번 선언을 해도 컴파일 시점에서 합쳐지기 때문에 확장성이 좋습니다.

다음 이유로 외부에 노출해야 하는 public API에 사용되는 타입은 항상 interface를 사용하여 작성해야 합니다.

따라서 일반적으로는 interface를 사용하고 union, tuple 등이 필요한 경우에만 type 별칭을 사용합니다.

 

extends, implements 사용

 

Type Alias도 상속, 확장의 개념에서 extendsimplements를 사용할 수 있지만 타입 정의 내에 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.
728x90

'TypeScript' 카테고리의 다른 글

2021/06/22 TypeScript  (0) 2021.06.22
2021/06/21 TypeScript  (0) 2021.06.21
2021/06/17 TypeScript  (0) 2021.06.17
2021/06/15 타입스크립트  (0) 2021.06.15
2021/06/11 타입스크립트  (0) 2021.06.11