refactor(typings): 改善和纠正各种 id 类型的性质 #481
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
各种 id 类型如:UserId, ProjectId, TaskId 等等,它们应该有下列性质:
const x: string = id as UserId
)const tid: TeamId = uid as UserId
会报错,需要手动强转)const id: UserId = 'hello'
会报错,需要手动强转)原来
interface X extends String { kind?: 'X' }
的实现,满足了2,但没有满足1、3。不满足1,导致当需要将 id 数据从带有场景上下文的业务代码传给不关心业务逻辑而只是简单接受 string 的底层组件时,需要通过
as string
强转,如果该信息包在一个对象结构里,那这个对象结构要么需要as any
,结果丢失所有类型信息,要么底层组件的对应对象结构类型声明就需要添加类型参数(泛型声明),结果增加冗长而意义不大的泛型声明。而不满足3,会漏掉很多类型检查,因为并不是任何 string 类型的值都可以赋值给特定 id 类型的。
新的写法是:
type X = string & { kind: 'X' }
,它能同时满足1、2、3、4,并在类型报错信息里有比较友好的信息提示。TODOs:
参考: