Below is my simplified TypeScript code snippet:
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
}
}
}
To prevent a compilation error, I am currently using the type assertion mentioned in the comment. However, it should be clear to humans that if the category
is 'timeout'
, then the option
is of type TimeoutOption
. How can I modify this without the need for a type assertion? Any suggestions for complete refactorings are appreciated.