[Typescript] Typescript에서 class가 다중상속을 지원하지 않는 이유 (다이아몬드 문제)
·
Programming/Typescript
만약 Typescript에서 class로 다중상속을 하려고 하면 에러가 발생한다. 예시를 통해서 확인해보자 아래와 같은 코드가 있다고 가정한다. class Test1 extends TestProblem { test() {} } class Test2 extends TestProblem { test() {} } // Error class Diamond extends Test1, Test2 {} 이렇게 2개 이상의 클래스를 상속받으려고 하면 에러가 난다. 다이아몬드 문제 왜 Typescript에서는 class의 다중상속을 막아두었을까? 조금 더 자세한 설명을 위해 다른 코드를 예시로 들어보자. class TestProblem { test(logString: string = 'TestProblem') { con..
[Typescript] typescript에서 type과 interface의 속성을 재정의하는 방법 (typescript Overriding)
·
Programming/Typescript
이 글에서는 typescript 환경에서 type또는 interface를 그대로 가져오며 타입 재정의가 필요한 속성을 재정의 하는 방법을 다룬다. type의 경우 예를 들어 아래와 같은 Test1 타입이 있다고 가정한다. type Test1 = { test1: string, test2: string, test3: number, }; const test1: Test1 = {test1: 'test1', test2: 'test2', test3: 3}; 이 때 Test1의 속성인 test3를 string 바꾼 새로운 타입이 필요하다고 가정한다. 그럴 때 아래와 같은 코드를 적용하면 된다. type Test2 = Omit & { test3: string }; const test2: Test2 = {test1: '..
[Mongoose] mongoose를 typescript와 사용하는 방법
·
Programming/Typescript
express에서 mongoose에 typescript를 적용하고 활용하는 방법에 대해서 서술한다. 크게 Schema 생성 방법, method 생성 방법, static 생성 방법 3가지를 알아보고 결과를 확인한다. 환경 mongoose: 6.x typescript: 4.5.4 node.js: 16.x mongoose에 typescript 적용 스키마 생성 static과 method를 사용하지 않는 mongoose의 Schema는 간단하게 정의할 수 있다. 1. 스키마에 들어갈 타입을 정의한다. interface DBUser { name: string; email: string; gender: boolean; } 2. 새로운 스키마를 생성하고 제네릭에 타입을 넣어준다. (이렇게 하면 스키마 정의시 타입을 ..
[Typescript] typescript 에서 filter 사용시 주의할 점
·
Programming/Typescript
typescript사용시 filter를 통해 undefined나 null을 배열에서 제거 할 때 타입이 제대로 잡히지 않는 현상이 일어났다. 해당일이 일어난 원인과 해결방법을 알아보자. 환경 typescript: 4.4.3 node.js: v16.15.0 문제 상황 아래와 같은 test 배열이 있다고 가정을 하고 값과 타입을 추론해보자. const test = ['test', 'test2', 'test3', undefined, 'test4', 'test5', undefined]; console.log(test); // ['test', 'test2', 'test3', undefined, 'test4', 'test5', undefined] 당연히 typescript에서 추론한 test의 타입은 (string..
얼은펭귄