In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what are the 1 bad habits of writing TypeScript code". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the 1 bad habits of writing TypeScript code".
1. What does the habit of not using strict mode look like
Tsconfig.json is not written in strict mode.
{"compilerOptions": {"target": "ES2015", "module": "commonjs"}} what should be done
Simply enable strict mode:
{"compilerOptions": {"target": "ES2015", "module": "commonjs", "strict": true}} Why do you have such a bad habit
It takes time to introduce stricter rules into an existing code base.
Why shouldn't we do this?
Stricter rules make it easier to maintain code in the future, saving you a lot of time.
two。 What does the habit of defining default values look like with | |
Use the old | | default values for processing backups:
Function createBlogPost (text: string, author: string, date?: Date) {return {text: text, author: author, date: date | | new Date ()}} what should be done
Use the new? Operator, or redefine the default value in the parameter.
Function createBlogPost (text: string, author: string, date: Date = new Date ()) return {text: text, author: author, date: date}} Why do you have such a bad habit?
?? The operator was introduced only last year, and when you use a value in a long function, it can be difficult to set it as the parameter default.
Why shouldn't we do this?
?? Different from | |? For null or undefined only, not for all imaginary values.
3. What does the habit of using any types at will look like?
When you are unsure of the structure, you can use the any type.
Async function loadProducts (): Promise {const response = await fetch ('https://api.mysite.com/products') const products: any = await response.json () return products} what should be done
Change any place in your code that uses any to unknown
Async function loadProducts (): Promise {const response = await fetch ('https://api.mysite.com/products') const products: unknown = await response.json () return products as Product []]} Why do you have such a bad habit
Any is convenient because it basically disables all type checking. Usually, any is used even in officially provided types. For example, the TypeScript team set the type of response.json () in the above example to Promise.
Why shouldn't we do this?
It basically disables all types of checking. Anything that comes in through any will completely abandon all types of checks. This will make the error difficult to catch.
4. What does val as SomeType's habit look like
Forcibly tell the compiler types that cannot be inferred.
Async function loadProducts (): Promise {const response = await fetch ('https://api.mysite.com/products') const products: unknown = await response.json () return products as Product []} what should be done
This is the opportunity for Type Guard to use his talents.
Function isArrayOfProducts (obj: unknown): obj isProduct [] {return Array.isArray (obj) & & obj.every (isProduct)} function isProduct (obj: unknown): obj isProduct {return obj! = null & & typeof (obj as Product). Id = = 'string'} async function loadProducts (): Promise {const response = await fetch (' https://api.mysite.com/products') const products: unknown = await response.json () if (! isArrayOfProducts (products)) {throw new TypeError (' Received malformed products API response')} return products} Why do you have such a bad habit
When moving from JavaScript to TypeScript, existing code bases often make assumptions about types that the TypeScript compiler cannot automatically infer. At this point, you can speed up the conversion through as SomeOtherType without having to modify the settings in tsconfig.
Why shouldn't we do this?
Type Guard ensures that all checks are clear.
5. What does the habit of as any in the test look like?
Create incomplete use cases when writing tests.
Interface User {id: string firstName: string lastName: string email: string} test ('createEmailText returns text that greats the user by first name', () = > {const user: User = {firstName:' John'} as any expect (createEmailText (user)) .toContain (user.firstName)} what should be done
If you need to simulate test data, move the simulation logic next to the object you want to simulate and make it reusable.
Interface User {id: string firstName: string lastName: string email: string} class MockUser implements User {id = 'id' firstName =' John' lastName = 'Doe' email =' john@doe.com'} test ('createEmailText returns text that greats the user by first name', () = > {const user = new MockUser () expect (createEmailText (user)) .toContain (user.firstName)} Why there is such a bad habit
When writing tests for code that does not yet have extensive test coverage, there is usually a complex big data structure, but only some of the specific functions to be tested are needed. You don't have to worry about other attributes in the short term.
Why shouldn't we do this?
In some cases, the code under test relies on attributes that we previously considered unimportant, and then all tests for that feature need to be updated.
6. What does the habit of optional attributes look like?
Mark attributes as optional, even if they sometimes do not exist.
Interface Product {id: string type: 'digital' |' physical' weightInKg?: number sizeInMb?: number} what should be done
Identify which combinations exist and which do not.
Interface Product {id: string type: 'digital' |' physical'} interface DigitalProduct extends Product {type: 'digital' sizeInMb: number} interface PhysicalProduct extends Product {type:' physical' weightInKg: number} Why do you have such a bad habit
It is easier to mark attributes as optional rather than split types and produces less code. It also requires a deeper understanding of the product being built and may limit the use of code if changes are made to the design of the product.
Why shouldn't we do this?
The biggest advantage of a type system is that compile-time checks can be used instead of run-time checks. With more explicit types, you can check for errors that may go unnoticed at compile time, such as ensuring that each DigitalProduct has a sizeInMb.
7. What does the habit of passing through the world with one letter look like
Name generics with one letter
Function head (arr: t []): t | what should undefined {return arr [0]} do?
Provide a complete descriptive type name.
Function head (arr: Element []): Element | undefined {return arr [0]} Why do you have this bad habit?
It was originally written in C++ 's stereotype library, and even official TS documents use an one-letter name. It can also be typed faster, simply typing the letter T instead of writing the full name.
Why shouldn't we do this?
Generic type variables are also variables, just like other variables. When IDE began to show us the type details of variables, we slowly gave up the idea of using their names to describe variable types. For example, we now write code with const name = 'Daniel', instead of const strName =' Daniel'. Similarly, one-letter variable names are often confusing because it is difficult to understand their meaning without looking at the declaration.
8. What does the habit of Boolean checking on non-Boolean values look like
Check whether a value is defined by passing the value directly to the if statement.
Function createNewMessagesResponse (countOfNewMessages?: number) {if (countOfNewMessages) {return `You have ${countOfNewMessages} new messages`} return 'Error: Could not retrieve number of new messages'} what should I do?
Check clearly what we are concerned about.
Function createNewMessagesResponse (countOfNewMessages?: number) {if (countOfNewMessages! = = undefined) {return `You have ${countOfNewMessages} new messages`} return 'Error: Could not retrieve number of new messages'} Why do you have such a bad habit
Writing short detection code looks more concise, allowing us to avoid thinking about what we actually want to test.
Why shouldn't we do this?
Maybe we should consider what we actually want to check. For example, the above example deals with the case where countOfNewMessages is 0 in different ways.
9. What does the habit of "great" operator look like?
Converts non-Boolean values to Boolean values.
Function createNewMessagesResponse (countOfNewMessages?: number) {if (!! countOfNewMessages) {return `You have ${countOfNewMessages} new messages`} return 'Error: Could not retrieve number of new messages'} what should I do?
Check clearly what we are concerned about.
Function createNewMessagesResponse (countOfNewMessages?: number) {if (countOfNewMessages! = = undefined) {return `You have ${countOfNewMessages} new messages`} return 'Error: Could not retrieve number of new messages'} Why do you have such a bad habit
For some people, understand! It's like an introduction to the world of JavaScript. It looks short and concise, and if you're used to it, you'll know what it means. This is a convenient way to convert any value to a Boolean value. Especially if there are no clear semantic boundaries between imaginary values, such as null, undefined, and''.
Why shouldn't we do this?
Like many convenient ways to code, use! It actually confuses the true meaning of the code. This makes it difficult for new developers to understand the code, both for the average developer and for JavaScript. It is also easy to introduce minor errors. The problem that countOfNewMessages is 0 is being used in Boolean checking for "non-Boolean values". Will still exist.
10.! = null what does this habit look like
The younger brother of the stick operator! = null enables us to check both null and undefined.
Function createNewMessagesResponse (countOfNewMessages?: number) {if (countOfNewMessages! = null) {return `You have ${countOfNewMessages} new messages`} return 'Error: Could not retrieve number of new messages'} what should be done
Check clearly what we are concerned about.
Function createNewMessagesResponse (countOfNewMessages?: number) {if (countOfNewMessages! = = undefined) {return `You have ${countOfNewMessages} new messages`} return 'Error: Could not retrieve number of new messages'} Why do you have such a bad habit
If there is no obvious difference between null and undefined in your code, then! = null helps simplify the inspection of both possibilities.
Why shouldn't we do this?
Although null was troublesome in the early days of JavaScript, when TypeScript was in strict mode, it could be a valuable tool in the language. A common pattern is to define the null value as something that does not exist, and the undefined as something unknown, for example, user.firstName = = null may mean that the user actually does not have a name, while user.firstName = = undefined simply means that we have not asked the user (and user.firstName = = means literally''.
Thank you for your reading, the above is "what are the bad habits of writing TypeScript code?" after the study of this article, I believe you have a deeper understanding of what are the bad habits of writing TypeScript code, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.