728x90

 

 


🚨 Interfaces

◽ javascript에서는 interfaces개념이 없다. 컴파일 되어도 js파일에 드러나지 않는다.

interfaces는 타입을 만들어내는 방식 중 하나로 외부적으로 드러나는 개체의 사용 방식이 적힌 타입

◽ 개체의 각 요소들의 타입을 편리하게 설정할 수 있다.


💻 interface1.ts

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

function hello1(person: Person1): void {
  console.log(`안녕 ${person.name}이야`)
}

const p1: Person1 = {
  name: 'Siot',
  age: 99
}

hello1(p1);

💻 컴파일 후 interface1.js

"use strict";
function hello1(person) {
    console.log(`안녕 ${person.name}이야`);
}
const p1 = {
    name: 'Siot',
    age: 99
};
hello1(p1);

 

 

 


optional property


물음표 ?

◽ 상황에 따라 필요할 때마다 선택적으로 사용

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

function hello2(person: Person2): void {
  console.log(`안녕 ${person.name}이야.`);
}

hello2({ name: 'siot' });

age?: number; : 있어도 없어도 되는 속성에는 ?를 붙인다

 

 

indexable types

◽ 인덱서의 타입은 string, number만 지정 가능

◽ (index의 타입을 string으로 하면) 어떤 것이든 []안에 프로퍼티 이름으로 지정 가능

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

function hello3(person: Person3): void {
  console.log(`안녕 ${person.name}이야.`);
}

const p31: Person3 = {
  name: 'Siot',
  age: 99
};

const p32: Person3 = {
  name: 'Kim',
  sisters: ['siot', 'ieung']
};

const p33: Person3 = {
  name: 'Lee',
  father: p31,
  mother: p32, 
}

hello3(p33)

 

 


function in interface

interface안에서 function정의하기


interface Person4 {
  name: string;
  age: number;
  hello(): void; //매개변수가 없는 hello함수의 리턴 타입void
}

 

💻 위 코드에서 interface Person4 내에 함수가 정의되는 방법

1️⃣ hello프로퍼티에 function함수를 할당할 수 있다. 또는

const p41: Person4 = {
  name: 'siot',
  age: 99,
  hello: function(): void {
    console.log(`안녕 ${this.name}이야.`);
  }
};

2️⃣ function 키워드 없이 hello함수 할당

const p42: Person4 = {
  name: 'siot',
  age: 99,
  hello(): void {
    console.log(`안녕 ${this.name}이야.`);
  }
};

3️⃣ 화살표함수

const p43: Person4 = {
  name: 'siot',
  age: 99,
  hello: (): void => {
    console.log(`안녕 ${this.name}이야.`); 
  }
};
// 화살표함수는 this를 사용할 수 없으므로 이 파일은 컴파일되지 않는다.

◽ 단, 화살표함수는 this를 사용할 수 없다.

 

💻 node를 이용해 함수 실행 결과

p41.hello();
p42.hello();

 

 


class implements interface

 ◽ interface를 이용해서 class만들기

 ◽ 외부로는 interface만 노출하고 내부적으로는 class구현을 하는 방식으로 객체 지향에서 많이 사용되는 방법이다.


💻 interface Iperson1 지정 후 class Person implements Iperson1까지만 작성하면 VSCode에서 자동으로 작성법 도움을 받을 수 있다. 에러가 발생하는 단어를 클릭 시 💡파란색전구 아이콘이 뜨는데 이거를 클릭하면 Iperson1변수의 인터페이스를 그대로 구현할 수 있다.

interface IPerson1 {
  name: string;
  age?: number;
  hello(): void;
}

class Person implements IPerson1 {}

💻 Iperson1을 구현하여 class Person으로 가져오기

(이때 name에 초기값을 지정해주지 않아 error가 발생하므로)

interface IPerson1 {
  name: string;
  age?: number;
  hello(): void;
}

class Person implements IPerson1 {
  name: string;
  age?: number | undefined;
  hello(): void {
    throw new Error("Method not implemented.");
  }
}

constructor생성자 함수를 만들어 name속성을 인수로 가져와 할당한다.

interface IPerson1 {
  name: string;
  age?: number;
  hello(): void;
}

class Person implements IPerson1 {
  name: string;
  age?: number | undefined;

  constructor(name: string) {
    this.name = name; 
  }

  hello(): void {
   console.log(`안녕! ${this.name}이야.`);
  }
  
}

 

💻 함수 실행

interface IPerson1 을 만족하는 class Person을 만들어서 type처럼 사용 가능하다. class이름으로 사용 가능하지만 interface이름으로 불러오는 게 정확한 표현이다. 

const person: IPerson1 = new Person("siot"); // constructor(name: string)
person.hello();

 

 


interface extends interface

 ◽ interface를 상속받아 interface만들기


💻 interface IKorean extends IPerson2 : IPerson2를 상속받는 IKoreanIPerson2의 내용을 모두 가질 수 있다.

interface IPerson2 {
  name: string;
  age?: number;
}

interface IKorean extends IPerson2 {
  city: string;
}

const k: IKorean = {
  name: 'siot',
  city: 'korea',
  age: 99,
}

 

 


function interface

 ◽ 함수에 대해 interface를 만드는 방법, 함수를 타이핑하는 방법


interface HelloPerson {
  (name: string, age?: number): void;
}

const helloPerson: HelloPerson = function(name: string) {
  console.log(`안녕! ${name}이야.`);
}

💻 function인수에 interface와 일치하지 않는 값을 넣었을 때 오류 예시

  ◽ interface HelloPerson의 optional property인 age?function인수에는 age:number로 할당할 때 일치하지 않은 에러임을 발생시킨다.

  ◽ 변수 helloPerson의 타입은 interface HelloPerson과만 관계를 맺으므로 function인수의 타입이 맞지 않을 때 오류가 날 수 있음을 이해하는 것이 중요

 

 


Readonly Interface Properties

 ◽ 함수에 대해 interface를 만드는 방법, 함수를 타이핑하는 방법


💻 속성 앞에 readonly붙여주기

interface Person8 {
  name: string;
  age?: number;
  readonly gender: string;
}

const p81: Person8 = {
  name: 'siot',
  gender: 'female',
}

p81.gender = "male";

 ◽ readonly는 새로운 값을 넣을 수 없다.

 ◽ interface를 만들 때 한 번 작성 후 바뀌지 않는 값 앞에는 readonly를 붙여주는 습관이 중요하다.

 ◽ interfacereadonly를 쓰면 class에서도 그대로 받아 쓰기 때문에 유용하다. 

readonly 속성 gender에 다른 값을 넣으려 할 때 error발생

 

 

 


🤷‍♀️ type alias VS interface

 ◽ 타입을 부르는 이름 VS 새로운 타입을 만들어내는 것

 ◽ 타입 별칭과 인터페이스 표기법의 차이점


💻 function 

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

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

💻 array 

// type alias
type PersonList = string[];

// interface
interface IPersonList {
  [index: number]: string; // indexable types
}

💻 intersection

interface ErrorHandling {
  success: boolean;
  error?: { message: string };
}

interface ArtistsData {
  artists: { name: string }[];
}

// type alias
type ArtistsResponseType = ArtistsData & ErrorHandling;

// interface
interface IArtistsResponse extends ArtistsData, ErrorHandling {} // 다중 상속

let art: ArtistsResponseType;
let iar: IArtistsResponse;

💻 union types

interface Bird {
  fly(): void;
  layEggs(): void;
}

interface Fish {
  swim(): void;
  layEggs(): void;
}

type PetType = Bird | Fish;

interface IPet extends PetType {} // error TS2312: An interface can only extend an object type or intersection of object types with statically known members.

class Pet implements PetType {} // error TS2422: A class can only implement an object type or intersection of object types with statically known members.

💻 Declaration Merging - interface

 ◽ type alias에서는 불가능한 기능

 ◽ interface 이름이 같을 때 합쳐짐

 ◽ htmlelements를 확장할 때 기존에 있는 interface에 추가하여 합칠 때, interface를 한번 더 선언하여 삽입하면 자동으로 합쳐져서 굳이 기존 내용을 작성할 필요가 없다.

interface MergingInterface {
  a: string;
}

interface MergingInterface {
  b: string;
}

let mi: MergingInterface;
mi.

 

728x90
+ Recent posts