Use ‘unknown’ instead of ‘any’ in TypeScript (Try / Catch error handling)

preview_player
Показать описание
Hi, I'm Wesley. I'm a brand ambassador for Kinde (paid sponsorship).

👉 Discord: all my courses have a private Discord where I actively participate

⏱️ Timestamps:
0:00 data: unknown
1:06 ts-reset
1:36 error: unknown
4:59 Handle unknown
8:03 Utility function

#typescript #typescripttutorial .
.
Рекомендации по теме
Комментарии
Автор

Wrapping an unknown in a String() call does not actually constitute casting, strictly speaking, as it’s either this <string> or this: as string. Wrapping stuff in a String() call actually replaces the value of the unknown with a string equivalent. Not casting

That note aside, I really like videos. Appreciate the effort

andrevinsky
Автор

Hello ByteGrad I was struggling with error handling and your tutorial really helped dealing with errors loved your content good luck

ismoiljonabduqahhorov
Автор

Thank you for explaining this well, i have banged my head on JS error handling for so long

elenamikhaylova
Автор

Your really good explaining, keep going Cheers

MailarYT
Автор

Hello, awesome channel for a noob like me! I was wondering, at 10:42 in our utility function couldn't we just omit to type the message as string and instead in the return do something like "return message.toString()" ?

honkhonkv
Автор

Your tutorials and content are A Class. Just get a better microphone if possible. Thanks

npaul
Автор

That's exactly how I handle request errors in our projects. 😅 Those Python develelopers cannot agree with Java developers on error response, and they both think it is easy to handle those errors in the client side.

grugbrain
Автор

We still not consider the case where "message" is also an object

SyTruong-dd
Автор

What about to save mark as 'any' and use following: console.log(error?.message || error?.stack || error); It is suitable for all error data types

antonapalanyuk
Автор

I didn't know there was an unknown type 😮

Axorax
Автор

Thanks.
export const getErrorMessage = (error: unknown) => {
if (error instanceof Error || (error && typeof error === "object" && "message" in error && typeof error.message === "string")) {
return error.message;
} else if (typeof error === "string") {
return error;
}
return "Something went wrong";
};

mryo_
Автор

I prefer
typeof error?.message === "string"

namstel
Автор

I would write
... else if (error && typeof error === "object" && "message in error && typeof error.message === "string") { ...
If there is a message in an error object but it isn't a string, it should possibly use the default error message instead.

AFE-GmdG
Автор

What if error.message is is an object, HTML, etc... Casting to string then would not be really safe.

deathone
Автор

just type and be happy:

error?.message??'errors happens'

supremecommanderz
Автор

the fn is async, and he used the then, man just use await

silenthooman