[Typescript] Tips: Ensure that all call sites must be given value

This one little tip has saved me hours of refactoring time. Passing string | undefined instead of ?: string ensures that ALL call sites must be given a value - amazing when you need to check every case in your repo.

interface UserInfo {
  name: string
}
// new requirement

interface UserInfo {
  name: string
  role?: 'admin'
}

// but now you need to search all the apperances where use UserInfo, not so convenient

// Instead, you can do:

interface UserInfo {
  name: string
  role: 'admin' | undefined
}

// now TS requries role to be present, now you got autocomplete and all the occurences where you need to update the code

// after you have doen the refactoring, you can chagne back to:
interface UserInfo {
  name: string
  role?: 'admin'
}

 

posted @ 2022-10-18 01:39  Zhentiw  阅读(21)  评论(0)    收藏  举报