음악, 삶, 개발

Typescript 로 Generic Class 생성하기. 본문

개발 Web/TypeScript

Typescript 로 Generic Class 생성하기.

Lee_____ 2022. 3. 15. 19:34

Class 를 만들다보면 constructor 의 인자로 어떠한 type 이

넘어올지 알수없다거나, 여러 type 들이 넘어올수있게끔 허용하고싶다.

물론 자바스크립트에서는 type 이 없으므로 어떠한 것이든 넘길수있지만,

Typescript generic class 를 사용함으로써 넘겨진 인자의 type 을 추후

개발하면서 체크할수있게된다.

 

문법은 클래스명에 <T> 를 붙여주고, 인자명에 T 를 붙여줘야한다.

class Foo<T> {

    constructor (public content: T) {}

}
   
new Foo ("one").content                                 // string
new Foo (["one"]).content                               // string[]
new Foo (1).content                                     // number
new Foo ([1]).content                                   // number[]
new Foo ({ one: "one" }).content                        // { one: "one" }
new Foo ({ one: 1 }).content                            // { one: 1 }
new Foo (document.createElement ("div")).content        // HTMLDivElement
new Foo (document.createElement ("button")).content     // HTMLButtonElement

위와 같이 작성해보면, 어떠한 인자를 넘겨도 content 속성에 접근했을때,

인자로 넘겨진 type 을 체크 할수있게된다. 

 

하지만 위와 같이 모든 type 을 다 넘기지않고, 몇몇의 type 으로만 제한하고싶을수있다.

이 경우에는 extends 를 붙이고 | 를 사용하여 원하는 type 들을 나열한다.

위의 코드를 보면, string | number 로 제한되었기때문에,

[1], 즉 number[] 는 넘길수없다는 error 가 표시된다.

위의 문법은 아래와 같이 작성될수도있다.

type MyType = string | number

class Foo<T extends MyType > {

    constructor (public content: T) {}

}

당연히 const enum 으로 제한할수도있다.

또는 또다른 class 로 제한할수도있다.

즉, Typescript 에서 Type 으로 취급하는 모든 녀석들을 extends 뒤에 전부 대입할수있다.