[TypeScript] Use the TypeScript "unknown" type to avoid runtime errors
The "any" type can be very useful, especially when adding types to an existing JavaScript codebase, but it can also lead to lots of runtime errors, as it provides no type-checking. The "unknown" type on the other hand, restricts developer from calling anything on it or assigning to any other type. The only way to use "unknown" variables is to apply logic flow type narrowing or casting, as that's the only way TypeScript can trust that it's dealing with a correct type. The "unknown" type is useful when building services or APIs that can return data of an unknown shape, so we might want to stop other developers from using it in potentially dangerous ways until it's been narrowed down to a specific type.
"any" type can pass in the compile phases without any problem, but will throw error in runtime.
We can use new type: 'unknown'.
For exmaple, we have code:
interface IComment { date: Date; message: string; } interface IDataService { getData(): unknown; } let service: IDataService; const response = service.getData();
You cannot directly use 'unknown' type, we have to tell Typescipt what type it is:
if(typeof response === 'string') { console.log(response.toUpperCase()); } else if(isComment(response)){ response.date; } function isComment(type: any): type is IComment { return (<IComment>type).message !== undefined && (<IComment>type).date !== undefined; }
相关文章
- 记录一次在生成数据库服务器上出现The timeout period elapsed prior to completion of the operation or the server is not responding.和Exception has been thrown by the target of an invocation的解决办法
- SQLBackupAndFTP The server principal "NT AUTHORITYSYSTEM" is not able to access the database "xxxx"
- [Typescript] Map a Discriminated Union to an Object
- [Typescript + React] Tip: Use generics in React to make dynamic and flexible components
- [Typescript Challenges] 3. Easy - Tuple to Object
- [Typescript] Convert a js project to typescript
- [React Typescript 2022] Refactor a React Component using TypeScript
- [Typescript] Narrow the unknown Type with TypeScript's Assertion Functions
- [Typescript] Ignore Null or Undefined Values with TypeScript Non-Null Assertion Operator
- [Typescript] Exclude Properties from a Type in TypeScript (Omit)
- [TypeScript] Use the never type to avoid code with dead ends using TypeScript
- [Typescript] Identity function pattern - Using Identity function to enforce the type 01
- [Typescript] Get a TypeScript package ready for release to NPM
- [Typescript] 45. Medium - MinusOne (Solution to solve max number of iteration by tail call)
- [Typescript] Tips: Use 'extends' keyword to narrow the value of a generic
- [Typescript] Tips: Use 'in' operator to transform a union to another union(watched)
- [Typescript] Convert a js project to typescript
- [React Typescript 2022] Use TypeScript to Type a React Class Component
- [Typescript] Ignore Null or Undefined Values with TypeScript Non-Null Assertion Operator
- AndroidStudio3.0 注解报错Annotation processors must be explicitly declared now. The following dependencies on the compile classpath are found to contain annotation processor.
- 【K3s】第25篇 解决The connection to the server localhost:8080 was refused
- The current user does not have write permissions to the target environment.
- EnvironmentNotWritableError: The current user does not have write permissions to the targe...
- 【已解决】RuntimeError: The following handlers are available to decode the pixel data however they are
- 问题解决:The connection to the server xxxxx:6443 was refused - did you specify the right host or port?