【发布时间】:2021-12-24 17:50:25
【问题描述】:
我试图创建一种类型,该类型会根据使用的枚举值而改变:
enum StatusEnum {
UPDATE = 'update',
CREATE = 'create'
}
type LogKeyType<K extends StatusEnum> =
K extends StatusEnum.UPDATE ? Record<string, any> : undefined
type Props = {
status: StatusEnum
log: LogKeyType<status> // <-- here is the key that should change type depending on status
// other keys...
}
对于这一行:log: LogKeyType<status> 我收到一条错误消息,指出状态指的是一个值,但被用作一种类型,我没有设法通过这个错误。
然后我也尝试使用泛型类型:
enum StatusEnum {
UPDATE = 'update',
CREATE = 'create'
}
type LogKeyType<K extends StatusEnum> =
K extends StatusEnum.UPDATE ? Record<string, any> : undefined
type Props<K extends StatusEnum> = {
status: K
log: LogKeyType<K>
// other keys...
}
但 typescript 无法分辨 log 的类型。
这是在这个用例中使用的:
if (props.status === StatusEnum.UPDATE) {
// do something with props.log that won't be undefined
}
我也可以直接检查日志是否未定义,但它不会那么花哨。
编辑:
这是我在 Baka 回答的评论中所说的错误:playground link
【问题讨论】:
标签: typescript types type-inference