从typescript中的属性值推断对象类型
我在打字稿中有以下代码(简化),
interface TimeoutOption {
category: 'timeout'
time: number
}
interface UserOption {
category: Parameters<typeof addEventListener>[0]
}
type MyDelayOptions = Array<TimeoutOption | UserOption>
function delay(options: MyDelayOptions) {
for (const option of options) {
if (option.category === 'timeout') {
timeout = setTimeout(() => {
// not relevant
}, option.time) // need to cast and do (option as TimeoutOption) to not get an error
}
}
}
以避免汇编错误,我必须添加评论中提到的类型断言。对于人类,尽管很明显,如果类别
是'timeout'
我的 option
是类型 timeoutoption
。如果没有类型的断言,我该如何使这项工作?欢迎完整的重构。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于
userOption
将类别
定义为 string (间接,但这就是它的出现)。结果,如果(option.category ==='timeout')
不区分您的两个工会成员,因为userOption
可以轻松地具有类别: “超时”
就像timeoutoption
也是如此。判别(<代码>类别)必须明确区分联盟,但在您的情况下并非如此。您可以测试
time
而不是(请参阅下面的***
):Playground link
The problem is that
UserOption
definescategory
as typestring
(indirectly, but that's what it comes out as). As a result,if (option.category === 'timeout')
doesn't discriminate between your two union members, becauseUserOption
could easily havecategory: "timeout"
just likeTimeoutOption
does. The discriminant (category
) has to clearly discriminate the union, but it doesn't in your case.You could test for the presence of
time
instead (see***
below):Playground link
看来您需要在此处使用一个典型的函数来确认
option
是类型timeoutoption
。https://www.typescriptlang.orgg/docs/handbook/handbook/handbook/adbook/advanced-tepes-.- html
这样的事情应该做到。
Playground link
Looks like you need a typeguard function here to confirm that
option
is of typeTimeoutOption
.https://www.typescriptlang.org/docs/handbook/advanced-types.html
Something like this should do it.
Playground link