【发布时间】:2018-10-24 14:59:38
【问题描述】:
我知道类型安全错误处理不是 ts 的原因是因为我们缺少函数中的 throws 子句。因此,每当我这样做时:
function mighThrow(input: number): void {
if (input === 1) {
throw new TypeError('cannot be one')
} else if(input === 2) {
throw new SyntaxError('invalid syntax: 2')
}
console.log('all good', input)
}
我无法准确输入错误:
try {
mighThrow(1)
} catch(e) {
// e is any, even though it could be TypeError | SyntaxError
}
问题与Promises 相同,捕获函数参数是硬编码的any:
interface Promise<T> {
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}
catch 的参数是 any。
所以我的问题是我该如何解决这个问题?如果我是库作者,是否有一种类型安全的方法可以帮助用户弄清楚他们到底在捕捉什么?我知道诸如添加Either 类型并每天调用它之类的解决方案,但这会强制当场处理错误,这只会将代码变成类似于语言会检查异常的东西。
【问题讨论】:
-
@JoeClay 那些激发这个问题的问题,感谢您链接它们!
标签: typescript error-handling try-catch