我在 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
}
}
}
为了避免编译错误,我必须添加注释中提到的类型断言。对于人类来说,很明显 if the category
is 'timeout'
my option
is of type TimeoutOption
。如果没有类型断言,我怎样才能使这项工作?欢迎完整的重构。
问题是UserOption
定义category
为类型string
(间接地,但这就是它的结果)。这样一来,if (option.category === 'timeout')
就不会歧视你的两个工会成员,因为UserOption
很容易就可以category: "timeout"
做到TimeoutOption
。判别式 ( category
) 必须明确区分工会,但在您的情况下并非如此。
您可以测试是否存在time
(见***
下文):
function delay(options: MyDelayOptions) {
for (const option of options) {
if ("time" in option) { // ***
const timeout = setTimeout(() => {
// not relevant
}, option.time) // need to cast and do (option as TimeoutOption) to not get an error
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句