Using the unknown keyword

Did you notice the unknown keyword used in the Fetch API example? Here's the code we are referring to: .then((jsonContent: unknown) >= ...​.

The unknown keyword was introduced with TypeScript 3.0. It is a type safe alternative to the any keyword that we have used so far in this book. With this keyword, we simply tell TypeScript that the type of the jsonContent object is not known at this point and that it should be checked before being manipulated. Basically, it means that the content should not be trusted and considered safe to use as is.

Anything can be assigned to a variable with the unknown type, but not the other way around. You cannot assign an object of type unknown to anything but itself and any unless you perform type checks to assert the type. Also, no operations can be applied to an unknown object without first performing type assertions.

Using unknown is heavily recommended over any when you want to clearly convey that some type checks must be performed before doing anything else. Using any doesn't enforce further type checks and thus, unknown is a safer option.

You can learn more and find many examples in the release notes of TypeScript 3.0: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.132.194