Typescript interface란?

Derek·2021년 3월 3일
1

typescript_study

목록 보기
4/6
post-thumbnail

안녕하세요, Derek 입니다. :)

지금 브레이브 걸스의 rollin 노래가 역주행해서 들어보니, 너무 신난다. 지금 신명나게 듣고 있네요.

오늘은 Typescript에서 꽤나 중요한 개념인 interface 에 대해서 정리해보려한다. 이는 Type Aliases 와 헷갈릴 내용이니, 다음 게시물과 많이 연관 지어서 설명을 해보려 한다.


1. interface 란?

타입스크립트 공식 문서에는 interface 의 정의를 다음과 같이 하고 있다.

One of TypeScript’s core principles is that type checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”. In TypeScript, interfaces fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.

쉽게 생각한다면, 같은 모양의 타입들을 naming하는 역할, 로 정리할 수 있겠다.

다시 한번 C++ 의 측면에서 바라본다면, typedef 와 같은 개념으로 봐도 될 것 같다.

더 빠른 이해를 위해 예를 들어보겠다

2. interface 써보기

가장 간단하게 예시이다.

interface User {
    age: number,
    name: string
}

User interface 는, agename 의 속성을 가지고 있는 인터페이스다. 하나의 타입을 딱 만들어서 이제 사용할 것이다! 라고 선언하는 것으로 생각해도 될 것 같다.

그렇다면 변수 타입을 하나 만들었으니, 아래와 같이 사용할 수 있겠다!

let seho: User = {
    age: 33,
    name: "seho"
}

seho 라는 변수를 만드는데, 그 seho 라는 변수의 타입은 내가 아까 만든 타입인 User 이다!

3. interface 활용

1) 객체 선언에 활용

위에서 선언한 User 인터페이스를 활용래보겠다.

function getUser(user: User) {
    console.log(user);
}

getUser(seho); // { "age": 33, "name": "seho"} 

getUser 라는 함수를 만들고, 그 함수 인자로는 User 타입의 객체를 넘겨준다.

해당 함수는 객체를 받아서 그대로 출력한다.

seho 를 받은 getUser 함수는 그대로 seho를 출력하겠죠.


물론 아래처럼도 활용할 수 있다.

const capt = {
    name: "captain",
    age: 100
}

getUser(capt); // { "age": 100, "name": "captain"} 

User 타입으로 capt 를 정의하진 않았지만, shape 이 같으므로 이상없이 돌아간다.

2) 함수의 스펙에 활용

interface 는 함수를 정의하는 모습에서도 활용이 가능하다.

interface SumFunction {
    (a: number, b: number) : number
}

SumFunction 에 사용되는 인자와 반환 타입에 대해서 인터페이스를 정의할 수 있고, 이를 아래와 같이 활용할 수 있다.

let sum: SumFunction;

sum = function(a, b){
    return a + b;
}

sum 이라는 객체를 만들고, 선언한 SumFunction 으로 타입을 지정한뒤, 정의하는 모습이다.

3) indexing 및 dictionary 활용

신박하긴 하지만, 개인적으로 굳이 이렇게 쓰일 일이 있을까, 하는 내용이긴 하다.

interface StringArray {
    [index: number]: string;
}

let arr: StringArray = ["a", "b"];

interface StringRegexDictionary {
    [key: string]: RegExp;
}

let objRegex: StringRegexDictionary = {
    cssFile: /\.css$/
}

StringArray 라는 interface 를 만들어서, arr 에게 그 타입을 지정했다.

StringArray 라는 interfaceindex 가 숫자고, 그 내용은 string 타입을 가지는 배열임을 알 수 있다.

굳이 저렇게 할 필요가 있을까.. 하지만 큰 그림이 있겠지, 믿는다.

Dictionary 타입도 같다.

4) 확장

이 부분이 뒤이어 업로드 될 type aliases 와 가장 큰 차이점이다.

interface 는 확장이 가능하다!!

거두절미하고 예를 보자.

interface Student {
    name: string,
    age: number;
}

interface graduantee extends Student{
    lan: string;
}

const tmp: graduantee = {
    lan : "C++",
    name: "Derek",
    age: 28
}

Student 라는 interface 를 선언했고, graduanteeStudent 를 상속받듯이 선언했다.

그렇다면 graduantee 인터페이스는 Student 인터페이스의 속성을 고대로 쓸 수 있다.

즉, 확장이 가능하다! (C++ 의 상속의 개념을 생각하면 편하다. )



이렇게 typescript 에서 꽤나 중요한 interface 문법을 정리해봤다.

틀린내용이다 수정사항이 발견되면 언제든지 댓글로 알려주세요.

감사합니다. 🙏

profile
Whereof one cannot speak, thereof one must be silent.

0개의 댓글