민자의 지식창고

Typescript 작성시 안좋은 습관 10가지 본문

개발노트/Javascript

Typescript 작성시 안좋은 습관 10가지

전지적민자시점 2021. 11. 4. 14:03

https://startup-cto.net/10-bad-typescript-habits-to-break-this-year/

 

10 bad TypeScript habits to break this year

TypeScript and JavaScript have steadily evolved over the last years, and some of the habits we built over the last decades have become obsolete. Some might never have been meaningful. Here's a list of 10 habits that we all should break.

startup-cto.net

 

원본은 위의 링크를 따라가면 됩니다.

 

Typescript를 작성시에 안좋은 습관들에 대해서 간단히 써보겠습니다.

꼭 지켜야 하는것은 아니지만, 안좋은 습관은 나중에 어디선가 문제가 발생할수 있습니다. 

미리 알아두고, 그때 그때 적용하는것이 좋은것 같습니다. 

 

1. tsconfig.json 에 strict mode를 사용을 하자.

Why?

엄격한 타입 체킹 옵션에 대한 활성화 여부로, 나중에 수정시에 더 쉽게 수정가능해준다고 합니다.

사실 체감하는 바를 못 겪으나, 빌드시 확실히 빨간불 쫘아악

tsconfig.json은 typescript는 javascript로 변환해 줄 트랜스파일러(컴파일러)가 필요하며, 아래는 옵션을 설정하는 파일입니다.

{ "compilerOptions": { "target": "ES2015", "module": "commonjs", "strict": true } }

 

2. default value를 정의 한다. 

function createBlogPost (text: string, author: string, date?: Date) {
  return {
    text: text,
    author: author,
    date: date || new Date()
  }
}

date를 보면 || 정의를 option 하게 정의 하고 있습니다. 그래서 아래와 같이 parameter에 정의를 해보았습니다(아래)

function createBlogPost (text: string, author: string, date: Date = new Date())
  return {
    text: text,
    author: author,
    date: date
  }
}

|| 을 쓰면, 나중 코드를 보다가 함수 안에 어떤 변수에서 무엇인 정의 설정되어 있는지 확인 하기가 어렵습니다.

 

3. any 대신 unKnown을 사용하자.

async function loadProducts(): Promise<Product[]> {
  const response = await fetch('https://api.mysite.com/products')
  const products: any = await response.json()
  return products
}

알려지지 않은 구조에 any로 type을 정의 하는데, unknown으로 정의 해봅시다.

 

Why?

any는 모든 타입 체크 타입이 비활성화 됩니다.

모든 유형 검사가 비활성화되고, (즉 무시를 함) 나중에 버그 잡기가 어려울수도 있습니다.

async function loadProducts(): Promise<Product[]> {
  const response = await fetch('https://api.mysite.com/products')
  const products: unknown = await response.json()
  return products as Product[]
}

4.  val as SomeType : 타입 체크

 

 

5. as any in tests 

일부 용도만 사용하는 경우, 재사용성을 위해서(복잡한 구조로 확장시) mockup을 만들어주는것이 좋습니다. 

interface User {
  id: string
  firstName: string
  lastName: string
  email: string
}

test('createEmailText returns text that greats the user by first name', () => {
  const user: User = {
    firstName: 'John'
  } as any
  
  expect(createEmailText(user)).toContain(user.firstName)
}

위의 일부 경우만 쓰는 경우

interface User {
  id: string
  firstName: string
  lastName: string
  email: string
}

class MockUser implements User {
  id = 'id'
  firstName = 'John'
  lastName = 'Doe'
  email = 'john@doe.com'
}

test('createEmailText returns text that greats the user by first name', () => {
  const user = new MockUser()

  expect(createEmailText(user)).toContain(user.firstName)
}

6. Optional properties

옵션의 프로퍼티들은 명확히 나누어서, 생성을 합시다. 부모와 자식간 상속을 잘 이용하여, 명확히 하는 방법이 좋습니다.

interface Product {
  id: string
  type: 'digital' | 'physical'
  weightInKg?: number
  sizeInMb?: number
}

2개가 옵션 프로퍼티를 공통된 부분 A클래스를 빼고 각각 상속받은 2개 클래스(B클래스, C클래스)로 다시 재분류하여 사용 합니다. 

 

7. Generic은 쉬운 단어로 사용하기

 

8. None-boolean boolean cheks 

 불리언 타입 체크시 !== undefined 를 사용합시다. 직관성 때문인것 같음.

 

9. !! 쓰지 말기

 

10. != null 과 != undefined를 정확히 이해하기

:null과 undefined를 철저히 구분 합니다.

null은 실제 값이 없음 의미 하고, undefined는 아직 값이 정해지지 않음을 의미 합니다.

8번, 9번, 10번은 추구하는 목정이 동일한것 같습니다. 

function createNewMessagesResponse (countOfNewMessages?: number) {
  if (countOfNewMessages != null) {
    return `You have ${countOfNewMessages} new messages`
  }
  return 'Error: Could not retrieve number of new messages'
}
function createNewMessagesResponse (countOfNewMessages?: number) {
  if (countOfNewMessages !== undefined) {
    return `You have ${countOfNewMessages} new messages`
  }
  return 'Error: Could not retrieve number of new messages'
}
728x90

'개발노트 > Javascript' 카테고리의 다른 글

동기와 비동기  (0) 2021.05.06
Array.prototype.find()  (0) 2021.04.13
Array.prototype.filter()  (0) 2021.04.12
Array-prototype.map()  (0) 2021.04.08
Angular Geolocation API  (0) 2021.02.16