[Typescript] Toolbox: isError
typescript toolbox
2023-09-14 09:00:45 时间
function isError(err: any): err is Error {
return err instanceof Error;
}
try {
somethingRisky()
} catch(err: unknown) {
if (isError(err)) {
console.log(err.stack)
} else {
console.log(err)
}
}
You can also have the following in test case, but do NOT put into production:
function assertIsError(err: any): asserts err is Error {
if(!(err instanceof Error)) throw new Error(`Not an error: ${err}`);
}
try {
somethingRisky();
} catch(err: unknown) {
// in a test case, you expect `err` must be an Error type
// if not, throw Error
assertIsError(err);
console.log(err.stack)
}
相关文章
- [Typescript] TS-toolbelt Split
- [Typescript] 29. Medium - ReplaceAll
- [Typescript] Declaration Merging
- [Typescript] asserts tips
- [React Native] Up & Running with React Native & TypeScript
- [Typescript] Create a Union From an Object's Values
- [Typescript 4.9] Auto-Accessors in Classes
- [Typescript] 110. Hard - Union to Tuple
- [!Typescript] Tips: Access deeper parts of objects and arrays
- [Typescript] Step5. Local types override
- [Typescript] “Record” Mapped Type
- [TypeScript] Using Assertion to Convert Types in TypeScript
- [TypeScript] Creating a Class in TypeScript
- [TypeScript] Distinguishing between types of Strings in TypeScript
- [TypeScript] type inference