Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why did TypeScript stop using any

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "why TypeScript stops using any". In daily operation, I believe many people have doubts about why TypeScript stopped using any. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the question of "why TypeScript stops using any". Next, please follow the editor to study!

What is any?

So any is neither a wildcard nor a base type, it explicitly interacts with third-party libraries. Then why does it often show up to you? Is it harmful to our system? Should we run from it or embrace it?

Any types are a powerful way to use existing JavaScript, allowing you to gradually choose to join and exit type checking during compilation.

The TypeScript document makes it clear that when we use the any type, we are telling the compiler:

When more than 500 contributors to the language offer help, we say no thank you. This sounds like choosing to exit the type checker, with which you cannot easily give up all security and confidence in the type system. We should use it to interact with untyped third-party (or first-party) Javascript code, or when we only know part of the type.

But wait, I have a lot of other reasons.

(1) won't TypeScript be converted to Javascript? isn't Javascript dynamic? Then why should I think about my type?

Right! But we write code in TypeScript, which is a statically typed language. One might say that statically typed languages do not produce less bug than dynamic languages. However, this is the worst of the two situations when using statically typed languages such as any.

(2) some parameters are difficult to enter correctly, but any is easier.

If we don't type correctly, we will write errors, more errors than we would write in dynamic languages, because we force TypeScript, a statically typed language, to check for incorrect types.

(3) I really don't know what the parameters are

Never mind! We can use unknown; it allows us to actually assign any type. However, we will not be allowed to use these values until a specific type is determined.

Type ParsedType = {id: number} const parseApiResponse (response: Record): ParsedType = > {const convertedResponse = (response as ParsedType) / / without doing the type cast we would / / get a type error here if (convertedResponse.id > = 0) {return convertedResponse} else {throw Error.new ("Invalid response"}})

(4) when adding types, I have to write a lot of code, and any has less work to do.

Maybe not, and if you write code that doesn't have a type, we may need to add defensive code to ensure that parameters and variables have the correct type so that the program can execute as expected. Any can't even prevent null or undefined from checking our logic.

/ / version 1 with `any` const fullName = (user: any) = > {if (user?.firstName & & user?.lastName) {return `{user.lastName}, ${user.firstName}`} return user?.firstName | | "} / / version 1 without `any` interface User {firstName: string lastName?: string} const fullName = ({firstName, lastName}: User) = > {if (lastName = = undefined) {return firstName} return `${lastName}, ${firstName}`;}

(5) types add a lot of complexity, and sometimes any is simpler.

Using any may allow us to develop more easily without considering how the data flows into the logic. But it shifts this burden to future readers of our code. They will have to explain what happened without context and compiler help.

(6) with documentation, I can provide all the contexts

When we add types, we get help from the compiler and documentation that does not decay over time, because our code will not compile if it is out of date.

Const intersection = (a: any, b: any): any = > {...} const intersection = (a: Set, b: Set): Set = > {...}

They are all equivalent, but the reader will have a better understanding of what the latter function is doing, rather than starting with the first function.

(7) I have written the code defensively through the necessary runtime checks to make sure there are no errors

There may be no errors now, but unless you have good test coverage, people who modify the code later will not believe that they are not refactoring in errors; just as the compiler will not help you, because we said it will not help you. If we explicitly set the type and change the API used in the system, the compiler will provide its guidance.

(8) what if I change my mind later? I might refactoring for a few hours.

We can always modify and adapt to new type definitions, and TypeScript provides a set of practical features for this. We can Pick the habit of selecting the desired properties from the previously defined types. Omit gets everything except a few. Partial makes all properties optional, or complete 180 and make all of them Requireds.

Type User = {id: number; firstName: string; lastName: string; age: number;} type UserParams = Pick & Partial const updateUser = ({id,... newUserParams}: UserParams) = > {{...}}

(9) good, delete any from TypeScript and open PR immediately

Let's take a deep breath, any. It's very powerful and useful under the right circumstances.

Interface with the library that uses it; make sure that the data is converted to the correct type as soon as possible before moving it to the system.

Resolve TypeScript type errors; if we find ourselves unable to enter something, any may be necessary. But it is recommended only after you have tried all other methods. If we use it, we should convert it back to a predictable type.

If our function can really handle any type, then this is rare and accidental (such as debugging or logging functions). In these cases, we need 100% assurance that there is no type that will cause the function to fail. We should examine the body of the function and determine and limit the most basic shape based on the input. For example, if we want to print something, we should at least verify that it responds to the toString.

At this point, the study on "Why TypeScript stopped using any" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report