【发布时间】:2018-11-29 03:53:01
【问题描述】:
我发现了一种情况,如果 typescript 中的 Enum 有 1 个或多个值,但我不明白为什么会有所不同。
看看这个简化的示例代码:
// library code
interface Action<T = any> {
type: T
}
interface SpecialAction<T = any> extends Action<T> {
id: string
timestamp: Date
}
function enhance<T>(action: Action<T>): SpecialAction<T> {
return {
... action,
id: "some-id",
timestamp: new Date()
}
}
// users code
enum ActionTypes {
A = "A"
}
interface UserAction extends SpecialAction<ActionTypes.A> {}
const value: UserAction = enhance({
type: ActionTypes.A
})
这工作得很好。但是,如果我像这样更改枚举:
enum ActionTypes {
A = "A",
B = "B"
}
然后我在const value: UserAction = enhance({ 的行中收到以下编译错误:
Type 'SpecialAction<ActionTypes>' is not assignable to type 'UserAction'.
Types of property 'type' are incompatible.
Type 'ActionTypes' is not assignable to type 'ActionTypes.A'.
如果我将代码更改为:
const value: UserAction = enhance<ActionTypes.A>({
type: ActionTypes.A
})
错误消失了,一切都恢复正常了。
所以我的假设是,当枚举只有一个值时,打字稿将类型 T 推断为 ActionTypes.A。但是如果枚举的值不止一个,那么 Typescript 就不能再推断了吗?
但为什么会这样呢?在给定的示例中,T 是 ActionTypes.A 的信息在对象文字中明确定义
{
type: ActionTypes.A
}
但更普遍的问题是: 为什么枚举值的数量对编译器很重要? 这不是很危险吗,因为它可能会以意想不到的方式破坏行为?
【问题讨论】:
标签: typescript