SlideShare una empresa de Scribd logo
1 de 26
Descargar para leer sin conexión
[TS] 4. Interface in TypeScript
by jbee
 interface 는자바스크립트개발자에게 친숙하지않은용어일꺼라고 생각
됩니다. 하지만정적타이핑에있어서큰부분을차지하고 있는syntax에대해
알아봅니다.
Contents
Interface?
Useful Interface
Available properties
Optional
readonly
Interface Type
Function Type
Indexable Type
Class interface
Interface?
 interface 란객체의껍데기 또는설계도라고 할수있을것 같습니다. 자바
스크립트에서는클래스도함수도결국 모두객체인데요, 클래스또는함수의
'틀'을정의할때사용할수있는것이인터페이스입니다.
여러함수가 특정한시그니처를동일하게 가져야할경우또는여러클래스가
동일한명세를정의해야하는경우인터페이스를통해서정의할수있습니다.
인터페이스는특정타입으로서사용될수있으며,  implements 의대상이될
수있습니다. 객체에인터페이스를적용하는경우또는반환값 등을설정할때
타입으로이용될수있습니다.
Useful Interface
함수에서어떤객체를받아야할경우, 해당type을어떻게 정의할수있을까
요?
위와같이 param 이라는인자의타입을literal 형식으로정의할수있습니다.
그런데그 객체의프로퍼티가 많아지는경우에는어떻게 정의할까요? (반환값
형식에 Promise<?> 형식으로지정을해줬는데요, 이는Generics 부분에서
다룰예정입니다.)
// AjaxUtils.ts
export async function fetchBasic(param: {url: string}): Promise
const response = await fetch(param.url);
return response.json();
}
literal로인자의타입을정의하다보니함수의signature가 너무길어졌습니다.
그런데여기서 Promise<Response> 이부분도정의가 필요합니다. 따라서
다음과 같이길어집니다.
export async function fetchData(param: {baseUrl: string, type
const {baseUrl, type, subject} = param;
const response = await fetch(`${baseUrl}/${subject}`);
const contentType = response.headers.get("content-type");
if (response.ok && contentType && contentType.includes(type
return response.json();
}
throw Error("Invalid baseUrl or subject");
}
export async function fetchData(param: {
baseUrl: string,
type: string,
subject?: string
}): Promise<{
id: number;
name: string;
company: string;
}[]> {
//...
}
뭔가 최대한가독성을좋게 하기 위해서개행을했지만성공하진못한것 같습
니다. 문제는여기서끝이아닙니다. 이함수를호출하는곳에서는다음과 같은
일이벌어집니다.
이혼란의상황을interface를통해깔끔하게 정리할수있습니다. 인자와반환
값을interface를통해정리해보겠습니다.
private async ajax(): Promise<{id: number; name: string; compan
const data: {id: number; name: string; company: string;}[] =
baseUrl: "http://localhost:3000",
subject: "users",
type: "application/json"
});
// ...do something
return data;
}
// interfaces.ts
interface Character {
id: number;
name: string;
company: string;
}
export interface dataFormat {
charaters: Character[];
}
export interface fetchDataParam {
baseUrl: string;
type: string;
subject: string;
}
위와같이 interfaces.ts 라는파일을생성하여인터페이스들을정의할수
있습니다.
 AjaxUtils.ts 에서는정의한인터페이스를import하여인자와반환값에
해당인터페이스를통해타입을정의할수있습니다.
// AjaxUtils.ts
import { fetchDataParam, dataFormat } from "./interfaces";
export async function fetchData(param: fetchDataParam): Promise
// ...
}
호출하는부분에서도마찬가지로 interfaces.ts 파일에서필요한인터페
이스를import하여타입을지정해줍니다. 예시코드에서처럼인터페이스를
정의하여인자에정의하던타입들을깔끔하게 정리할수있습니다. 또한다른
파일에서해당함수를정의하는부분과 호출하는부분이다를때, 하나의인터
페이스를공유할수있습니다. 인터페이스를통일시키는것이중요할때매우
유용하게 사용할수있습니다.
// Controller.ts
import { fetchDataParam, dataFormat } from "./interfaces";
private async ajaxCall(): Promise<dataFormat> {
const param: fetchDataParam = {
baseUrl: "http://localhost:3000",
subject: "users",
type: "application/json"
};
const data: dataFormat = await fetchData(param);
console.log(data);
return data;
}
Available properties
인터페이스에도클래스와동일하게 optional하게 property를지정할수있으
며readonly 타입으로property를지정할수있습니다.
optional property로지정한 amount 에대해서는구현하지않아도에러가
발생하지않는것을확인할수있습니다.
Readonly properties
export interface WeatherSpec {
readonly type: string;
amount: number;
}
const rainfall: WeatherSpec = {
type: "rainfall",
amount: 24,
}
rainfall.type = "snow"; // Error!
rainfall.amout += 3; // OK!
에러메시지는다음과 같습니다.  [!] Error: Cannot assign to
'type' because it is a constant or a read-only property. 
위와같이interface에서readonly로지정한프로퍼티에대해서는그 값을바
꿀수없습니다. 이는변수를사용할때사용하는 const 키워드와동일한역
할을수행한다고 이해할수있습니다.
Function Type
인터페이스의프로퍼티로함수의시그니처를정의할수있습니다. 반환하는형
식또는그 값이다르지만시그니처를통일시켜야하는경우가 존재할수있습
니다. 그럴경우다음과 같이interface를설계하여함수를구현할수있습니
다.
반환타입을제외하고 동일한형식의함수를정의했습니다. 이것은특정콜백
함수를받는함수를구현할때그 유용성이더빛을발합니다.
interface TimeFunc {
(hour: number, minutes: number): any;
}
const buildTimeStamp: TimeFunc = (hour, minutes): number =>
if (minutes < 10) {
return Number(`${hour}0${minutes}`);
}
return Number(`${hour}${minutes}`);
}
const buildTimeText: TimeFunc = (hour, minutes): string =>
if (minutes < 10) {
return `${hour}시 0${minutes}분`;
}
return `${hour}시 ${minutes}분`;
}
buildTimeStamp(12, 33); //1233
buildTimeText(12, 33); //12시 33분
콜백함수를인자로받을때해당하는시그니처가 통일되어야하는부분을인
터페이스를통해해결할수있습니다.
const buildTime = (timeText: string, cb: TimeFunc) => {
const hour: number = Number(timeText.split(":")[0]);
const minutes: number = Number(timeText.split(":")[1]);
return cb(hour, minutes);
}
console.log(buildTime("12:33", buildTimeStamp)); //1233
console.log(buildTime("12:33", buildTimeText)); //12시 33분
Indexable Types
자바스크립트에서다음과 같은코드는매우자연스럽습니다.
const obj = {
first: 1,
second: 2,
};
Object.keys(obj).forEach(key => console.log(obj[key]));
즉, 객체의프로퍼티에접근할때, 동적으로생성된 key 를통해객체의프로
퍼티에 [] 표기법으로접근하는경우입니다. 하지만이코드는타입스크립트
에서동작하지않습니다.
 [!] Element implicitly has an 'any' type because type '{
first: number; second: number; }' has no index
signature. 이란에러를발생시킵니다. 왜냐하면정의한 obj 라는객체에
index signature가 없기 때문입니다. 따라서이에러는다음과 같이해결할수
있습니다.
interface Indexable {
[key: string]: any;
};
const obj: Indexable = {
first: 1,
second: 2,
};
Object.keys(obj).forEach((key: string) => obj[key]);
 Indexable 이란이름의인터페이스를정의해준다음,  string 타입의key
에 any 타입을지정해줍니다. 이인터페이스를통해서객체를생성하면 [] 
표기법을통해객체의프로퍼티에접근할수있습니다.
Class interface
인터페이스를클래스에서도사용할수있습니다. 상위클래스를 extends 라
는키워드로상속하듯이 implements 라는키워드로인터페이스를구현할
수있습니다. 클래스는인터페이스를 implements 하면서인터페이스에명
세되어있는기능들을구현해야하는의무를갖게 됩니다.
인터페이스에서는클래스의프로퍼티(필드멤버), 메소드등을정의할수있습
니다. 또한optional 한명세또한정의할수있습니다.
interface Movable {
velocity: number;
move(time: number): Position;
startPos?: Position;
}
class BMWCar implements Movable {
}
여기까지입력했을때나타나는에러메세지는다음과 같습니다.  [!] Class
'Car' incorrectly implements interface 'Movable'. . 특정인터
페이스를구현한클래스는인터페이스에정의된명세를구현해야합니다.
즉여기서는 velocity 라는프로퍼티를포함해야하며,  move 라는메소드
를구현해야만합니다. 이 BMWCar 클래스는생성할때다음과 같이생성할
수있습니다.
class BMWCar implements Movable {
velocity: number;
constructor(velocity) {
this.velocity = velocity;
}
move(time: number): Position {
//... do something
}
}
const bmw: Movable = new BMWCar();
 BMWCar 라는타입말고도해당클래스에서구현한인터페이스인 Movable 
타입으로지정할수있습니다.
Public Property
TypeScript Official Document에 Interfaces describe the public
side of the class, rather than both the public and private
side. 이런말이나옵니다.  인터페이스 를통해구현해야함을명시하는메소
드는 private 접근 제어자로정의될메소드가 아니라 public 접근 제어
자로정의될메소드이어야한다고 합니다.
즉, 인터페이스를통해명세를정의할때는 private 속성말고  public 속
성에대해정의합니다.
마무리
인터페이스를통해보다세밀한구조설계와추상화가 가능해졌습니다. 해당
포스팅외다른타입스크립트포스팅은여기에서보실수있으며예제에사용
된코드는여기에서확인하실수있습니다.
감사합니다.
3. Interface in TypeScript end

Más contenido relacionado

La actualidad más candente

More effective c++ 2
More effective c++ 2More effective c++ 2
More effective c++ 2
현찬 양
 
More effective c++ 1
More effective c++ 1More effective c++ 1
More effective c++ 1
현찬 양
 
Effective c++ chapter5 6_ 131039 신동찬
Effective c++ chapter5 6_ 131039 신동찬Effective c++ chapter5 6_ 131039 신동찬
Effective c++ chapter5 6_ 131039 신동찬
Dong Chan Shin
 
이펙티브 C++ (7~9)
이펙티브 C++ (7~9)이펙티브 C++ (7~9)
이펙티브 C++ (7~9)
익성 조
 
가능한 C++ 스타일의 캐스트를 즐겨 쓰자
가능한 C++ 스타일의 캐스트를 즐겨 쓰자가능한 C++ 스타일의 캐스트를 즐겨 쓰자
가능한 C++ 스타일의 캐스트를 즐겨 쓰자
민욱 이
 
Effective c++ 3
Effective c++ 3Effective c++ 3
Effective c++ 3
현찬 양
 
보다 나은 웹 어플리케이션 설계
보다 나은 웹 어플리케이션 설계보다 나은 웹 어플리케이션 설계
보다 나은 웹 어플리케이션 설계
Eb Styles
 
More effective c++ 3
More effective c++ 3More effective c++ 3
More effective c++ 3
현찬 양
 
이펙티브 C++ 공부
이펙티브 C++ 공부이펙티브 C++ 공부
이펙티브 C++ 공부
quxn6
 
Effective c++ chapter 7,8
Effective c++ chapter 7,8Effective c++ chapter 7,8
Effective c++ chapter 7,8
문익 장
 
M1 2 1
M1 2 1M1 2 1
M1 2 1
nexthw
 

La actualidad más candente (20)

Clean code(03)
Clean code(03)Clean code(03)
Clean code(03)
 
모어 이펙티브 c++ 1,2장 스터디
모어 이펙티브 c++ 1,2장 스터디모어 이펙티브 c++ 1,2장 스터디
모어 이펙티브 c++ 1,2장 스터디
 
More effective c++ 2
More effective c++ 2More effective c++ 2
More effective c++ 2
 
More effective c++ 1
More effective c++ 1More effective c++ 1
More effective c++ 1
 
Effective c++ chapter5 6_ 131039 신동찬
Effective c++ chapter5 6_ 131039 신동찬Effective c++ chapter5 6_ 131039 신동찬
Effective c++ chapter5 6_ 131039 신동찬
 
이펙티브 C++ (7~9)
이펙티브 C++ (7~9)이펙티브 C++ (7~9)
이펙티브 C++ (7~9)
 
가능한 C++ 스타일의 캐스트를 즐겨 쓰자
가능한 C++ 스타일의 캐스트를 즐겨 쓰자가능한 C++ 스타일의 캐스트를 즐겨 쓰자
가능한 C++ 스타일의 캐스트를 즐겨 쓰자
 
Effective c++ 3
Effective c++ 3Effective c++ 3
Effective c++ 3
 
보다 나은 웹 어플리케이션 설계
보다 나은 웹 어플리케이션 설계보다 나은 웹 어플리케이션 설계
보다 나은 웹 어플리케이션 설계
 
이펙티브 C++ 스터디
이펙티브 C++ 스터디이펙티브 C++ 스터디
이펙티브 C++ 스터디
 
More effective c++ 3
More effective c++ 3More effective c++ 3
More effective c++ 3
 
이펙티브 C++ 공부
이펙티브 C++ 공부이펙티브 C++ 공부
이펙티브 C++ 공부
 
[ES6] 11. Modularization, import와 export
[ES6] 11. Modularization, import와 export[ES6] 11. Modularization, import와 export
[ES6] 11. Modularization, import와 export
 
Effective c++ chapter 7,8
Effective c++ chapter 7,8Effective c++ chapter 7,8
Effective c++ chapter 7,8
 
Effective C++ Chapter 1 Summary
Effective C++ Chapter 1 SummaryEffective C++ Chapter 1 Summary
Effective C++ Chapter 1 Summary
 
javascript01
javascript01javascript01
javascript01
 
effective c++ chapter 3~4 정리
effective c++ chapter 3~4 정리effective c++ chapter 3~4 정리
effective c++ chapter 3~4 정리
 
Chapter7~9 ppt
Chapter7~9 pptChapter7~9 ppt
Chapter7~9 ppt
 
[Toolcon2014] WebStorm에서 자바스크립트 리팩토링하기
[Toolcon2014] WebStorm에서 자바스크립트 리팩토링하기[Toolcon2014] WebStorm에서 자바스크립트 리팩토링하기
[Toolcon2014] WebStorm에서 자바스크립트 리팩토링하기
 
M1 2 1
M1 2 1M1 2 1
M1 2 1
 

Similar a 04. interface in typescript

Similar a 04. interface in typescript (20)

[HaU] 신입 기술 면접 준비 java
[HaU] 신입 기술 면접 준비 java[HaU] 신입 기술 면접 준비 java
[HaU] 신입 기술 면접 준비 java
 
C++ api design 품질
C++ api design 품질C++ api design 품질
C++ api design 품질
 
이펙티브 C++ 789 공부
이펙티브 C++ 789 공부이펙티브 C++ 789 공부
이펙티브 C++ 789 공부
 
Start IoT with JavaScript - 6.함수
Start IoT with JavaScript - 6.함수Start IoT with JavaScript - 6.함수
Start IoT with JavaScript - 6.함수
 
Java(3/4)
Java(3/4)Java(3/4)
Java(3/4)
 
[스프링 스터디 3일차] AOP와 LTW
[스프링 스터디 3일차] AOP와 LTW[스프링 스터디 3일차] AOP와 LTW
[스프링 스터디 3일차] AOP와 LTW
 
The art of readable code ch4 ch8
The art of readable code ch4   ch8The art of readable code ch4   ch8
The art of readable code ch4 ch8
 
[SwiftStudy 2016] 3장. 함수
[SwiftStudy 2016] 3장. 함수[SwiftStudy 2016] 3장. 함수
[SwiftStudy 2016] 3장. 함수
 
[스프링 스터디 1일차] 템플릿
[스프링 스터디 1일차] 템플릿[스프링 스터디 1일차] 템플릿
[스프링 스터디 1일차] 템플릿
 
자바 8 학습
자바 8 학습자바 8 학습
자바 8 학습
 
C# 개요 및 소개 [ 유니티 및 C# 스터디 / 2024-04-19 ]
C# 개요 및 소개 [ 유니티 및 C# 스터디 / 2024-04-19 ]C# 개요 및 소개 [ 유니티 및 C# 스터디 / 2024-04-19 ]
C# 개요 및 소개 [ 유니티 및 C# 스터디 / 2024-04-19 ]
 
Effective c++chapter4
Effective c++chapter4Effective c++chapter4
Effective c++chapter4
 
Java collections framework
Java collections frameworkJava collections framework
Java collections framework
 
Rails style-guide-2
Rails style-guide-2Rails style-guide-2
Rails style-guide-2
 
주니어 개발자도 이해 할 수 있는 Go - Scope 편
주니어 개발자도 이해 할 수 있는 Go - Scope 편주니어 개발자도 이해 할 수 있는 Go - Scope 편
주니어 개발자도 이해 할 수 있는 Go - Scope 편
 
Scala 기초 (2)
Scala 기초 (2)Scala 기초 (2)
Scala 기초 (2)
 
Isomorphicspring Isomorphic - spring web seminar 2015
Isomorphicspring Isomorphic - spring web seminar 2015Isomorphicspring Isomorphic - spring web seminar 2015
Isomorphicspring Isomorphic - spring web seminar 2015
 
읽기 좋은 코드가 좋은코드다
읽기 좋은 코드가 좋은코드다읽기 좋은 코드가 좋은코드다
읽기 좋은 코드가 좋은코드다
 
Scala self type inheritance
Scala self type inheritanceScala self type inheritance
Scala self type inheritance
 
2014-15 Intermediate C++ Study #7
2014-15 Intermediate C++ Study #72014-15 Intermediate C++ Study #7
2014-15 Intermediate C++ Study #7
 

Más de Han JaeYeab

Más de Han JaeYeab (19)

07. type system
07. type system07. type system
07. type system
 
06. decorator
06. decorator06. decorator
06. decorator
 
05. generics in typescript
05. generics in typescript05. generics in typescript
05. generics in typescript
 
03. function in typescript
03. function in typescript03. function in typescript
03. function in typescript
 
02. class in typescript
02. class in typescript02. class in typescript
02. class in typescript
 
01. basic types
01. basic types01. basic types
01. basic types
 
intro. typescript playground
intro. typescript playgroundintro. typescript playground
intro. typescript playground
 
[ES6] 12. Array
[ES6] 12. Array[ES6] 12. Array
[ES6] 12. Array
 
[ES6] 10. Generator
[ES6] 10. Generator[ES6] 10. Generator
[ES6] 10. Generator
 
[ES6] 9. Iterator
[ES6] 9. Iterator[ES6] 9. Iterator
[ES6] 9. Iterator
 
[ES6] 8. Symbol
[ES6] 8. Symbol[ES6] 8. Symbol
[ES6] 8. Symbol
 
[ES6] 7. Template literal
[ES6] 7. Template literal[ES6] 7. Template literal
[ES6] 7. Template literal
 
[ES6] 6. Class
[ES6] 6. Class[ES6] 6. Class
[ES6] 6. Class
 
[ES6] 5. Destructuring
[ES6] 5. Destructuring[ES6] 5. Destructuring
[ES6] 5. Destructuring
 
[ES6] 4. Spread, Rest parameter
[ES6] 4. Spread, Rest parameter[ES6] 4. Spread, Rest parameter
[ES6] 4. Spread, Rest parameter
 
[ES6] 3. iteration
[ES6] 3. iteration[ES6] 3. iteration
[ES6] 3. iteration
 
[ES6] 2. arrow function
[ES6] 2. arrow function[ES6] 2. arrow function
[ES6] 2. arrow function
 
[ES6] 1. let과 const
[ES6] 1. let과 const[ES6] 1. let과 const
[ES6] 1. let과 const
 
클라우드 컴퓨팅에 대한 기본적인 이해
클라우드 컴퓨팅에 대한 기본적인 이해클라우드 컴퓨팅에 대한 기본적인 이해
클라우드 컴퓨팅에 대한 기본적인 이해
 

04. interface in typescript