【发布时间】:2020-01-02 10:40:42
【问题描述】:
我在操场上有一个 TypeScript 代码 sn-p。请查看TypeScript playground 或此处:
enum MyTypes {
FIRST = "FIRST",
SECOND = "SECOND",
THIRD = "THIRD"
}
type TFirst = {
type: MyTypes.FIRST
foo: string
}
type TSecond = {
type: MyTypes.SECOND
foo: string
}
type TThird = {
type: MyTypes.THIRD
bar: string
}
type TConditionalType<T> =
T extends MyTypes.FIRST ? TFirst :
T extends MyTypes.SECOND ? TSecond :
T extends MyTypes.THIRD ? TThird :
null
const getMyObjectBasedOnType = <T extends MyTypes>(type: T): TConditionalType<T> | null => {
switch (type) {
case MyTypes.FIRST: {
return {
type: MyTypes.FIRST,
foo: 'test'
}
}
default: {
return null
}
}
}
const firstObject = getMyObjectBasedOnType(MyTypes.FIRST)
// firstObject is type of TFirst or null which is okay
if (firstObject) {
firstObject.foo
}
有一个函数getMyObjectBasedOnType(type: T),它根据type 参数返回一个条件类型的对象。这似乎有效,因为末尾的firstObject 是TFirst | null 类型。一切都在这里。
当我返回对象时,我遇到的问题是第 31 行提到的函数中出现 TypeScript 错误。我明白了:
Type '{ type: MyTypes.FIRST; foo: string; }' is not assignable to type 'TConditionalType<T>'. 我不知道出了什么问题。据我了解,这是TFirst 的对象,应该没问题。为什么我会收到此错误,什么是正确的解决方法?
【问题讨论】:
标签: javascript typescript enums conditional-types