首页 > 其他分享 >[Typescript] Tips: Ensure that all call sites must be given value

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

时间:2022-10-18 01:56:02浏览次数:49  
标签:given Typescript name sites role UserInfo interface now string

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'
}

 

标签:given,Typescript,name,sites,role,UserInfo,interface,now,string
From: https://www.cnblogs.com/Answer1215/p/16801261.html

相关文章