In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you what are the common types of TypeScript, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Common types (Everyday Types)
Types can appear in many places, not just in type comments (type annotations). We need to learn not only the types themselves, but also where to use them to produce new structures.
Let's first review the most basic and common types, which are the basis for building more complex types.
Original type:
String,number and boolean (The primitives)
JavaScript has three very common primitive types: string,number and boolean, each of which has a corresponding type in TypeScript. Their names are the same as what you get when you use the typeof operator in JavaScript.
String represents a string, such as "Hello, world"
Number represents a number. For example, there is no int or float in 42Jet JavaScript. All numbers are of type number.
Boolean represents a Boolean value, but there are actually only two values: true and false
Type names String, Number, and Boolean (capital letters) are also legal, but they are very rare special built-in types. So types always use string, number, or boolean.
Array (Array)
To declare an array type similar to [1,2,3], you need to use the syntax number []. This syntax can be applied to any type (for example, string [] represents an array of strings). You may also see that this way of writing Array is the same. We will introduce T grammar to you in the generics section.
Any
TypeScript has a special type, any, which can be set to any when you don't want a value to cause a type checking error.
When a value is of type any, you can get any of its properties (which can also be converted to type any), or call it like a function to assign it to a value of any type, or assign a value of any type to it, or any other syntactically correct operation:
Let obj: any = {x: 0}; / / None of the following lines of code will throw compiler errors.// Using `any` disables all further type checking, and it is assumed / / you know the environment better than TypeScript.obj.foo (); obj (); obj.bar = 100 const obj = "hello"; const n: number = obj
The any type is useful when you don't want to write a long type code and just want TypeScript to know that a particular piece of code is fine.
NoImplicitAny
If you do not specify a type and TypeScript cannot infer its type from the context, the compiler will default to the any type.
If you always want to avoid this situation, after all, TypeScript does not do type checking on any, you can turn on the compilation item noImplicitAny, and when it is implicitly inferred as any, TypeScript will report an error.
Type comments on variables (Type Annotations on Variables)
When you declare a variable using const, var, or let, you can optionally add a type annotation to explicitly specify the type of variable:
Let myName: string = "Alice"
TypeScript does not use the form of "type declaration on the left", such as int x = 0; type annotations often follow the content of the type to be declared.
But most of the time, it's not necessary. Because TypeScript automatically infers types. For example, the type of a variable can be inferred based on the initial value:
/ / No type annotation needed-- 'myName' inferred as type' string'let myName = "Alice"
Most of the time, you don't need to learn the rules of inference. If you are just getting started, try to use as few type annotations as possible. You may be surprised that TypeScript needs very little content to fully understand what is going to happen.
Function (Function)
Function is the main method for JavaScript to transmit data. TypeScript allows you to specify the type of input value and output value of the function.
Parameter type comments (Parameter Type Annotations)
When you declare a function, you can add a type comment to each parameter to declare what type of parameter the function can accept. The parameter type comment is followed by the parameter name:
/ / Parameter type annotationfunction greet (name: string) {console.log ("Hello," + name.toUpperCase () + "!");}
When the parameter has a type annotation, TypeScript checks the argument of the function:
/ / Would be a runtime error if executable greet (42); / / Argument of type 'number' is not assignable to parameter of type' string'.
Even if you do not make type comments on the parameters, TypeScript will still check whether the number of parameters passed in is correct
Return value type comment (Return Type Annotations)
You can also add type comments for the return value. The type comment of the return value follows the parameter list:
Function getFavoriteNumber (): number {return 26;}
Like variable type annotations, you don't always need to add return value type annotations. TypeScript infers the return type of a function based on its return statement. In this example, type annotations are the same as unwritten, but some code bases explicitly specify the type of return value, either because of the need to document, or to prevent accidental changes, or just a personal preference.
Anonymous function (Anonymous Functions)
Anonymous functions are a little different from function declarations. When TypeScript knows how an anonymous function will be called, the parameters of the anonymous function are automatically specified.
This is an example:
/ / No type annotations here, but TypeScript can spot the bugconst names = ["Alice", "Bob", "Eve"]; / / Contextual typing for functionnames.forEach (function (s) {console.log (s.toUppercase ()); / / Property 'toUppercase' does not exist on type' string'. Did you mean 'toUpperCase'?}); / / Contextual typing also applies to arrow functionsnames.forEach ((s) = > {console.log (s.toUppercase (); / / Property' toUppercase' does not exist on type 'string'. Did you mean 'toUpperCase'?})
Although the parameter s does not add a type annotation, TypeScript infers the type of s based on the type of the forEach function and the type of the array passed in.
This process is called context inference (contextual typing) because it is inferred from the context in which the function appears that it should have the type.
Like the inference rule, you don't need to learn how it happens, just know that it does exist and help you leave out some unnecessary comments. Later, we will see more examples of how the context in which a value occurs affects its type.
Object type (Object Types)
In addition to primitive types, the most common type is the object type. To define an object type, we simply list its properties and corresponding types.
For example:
/ / The parameter's type annotation is an object typefunction printCoord (pt: {x: number; y: number}) {console.log ("The coordinate's x value is" + pt.x); console.log ("The coordinate's y value is" + pt.y);} printCoord ({x: 3, y: 7})
Here, we add a type to the parameter, which has two properties, x and y, both of which are number types. You can use, or; separate attributes, with or without the delimiter of the last attribute.
The type corresponding to each attribute is optional. If you do not specify it, the any type is used by default.
Optional attribute (Optional Properties)
The object type can specify that some or even all of the properties are optional, you only need to add one after the property name:
Function printName (obj: {first: string; last?: string}) {/ /...} / / Both OKprintName ({first: "Bob"}); printName ({first: "Alice", last: "Alisson"})
In JavaScript, if you get an attribute that doesn't exist, you get a undefined instead of a run-time error. Therefore, when you get an optional property, you need to check whether it is undefined before using it.
Function printName (obj: {first: string; last?: string}) {/ / Error-might crash if 'obj.last' wasn't provided! Console.log (obj.last.toUpperCase ()); / / Object is possibly 'undefined'. If (obj.last! = = undefined) {/ / OK console.log (obj.last.toUpperCase ());} / / A safe alternative using modern JavaScript syntax: console.log (obj.last?.toUpperCase ());} Union type (Union Types)
The TypeScript type system allows you to use a series of operators to build new types based on existing types. Now that we know how to write some basic types, it's time to put them together.
Define a federated type (Defining a Union Type)
The first way to combine types is to use federated types, a federated type is a type consisting of two or more types, indicating that the value may be any of these types. Each of these types is a member of the federated type (members).
Let's write a function to deal with strings or numbers:
Function printId (id: number | string) {console.log ("Your ID is:" + id);} / / OKprintId (101); / / OKprintId ("202"); / / ErrorprintId ({myID: 22342}); / / Argument of type'{myID: number;}'is not assignable to parameter of type 'string | number'.// Type' {myID: number;}'is not assignable to type 'number'. Use federated types (Working with Union Types)
It is easy to provide a value that matches the union type, you only need to provide a value that matches any one of the union member types. So after you have a value of a union type, how do you use it?
What TypeScript will ask you to do must be valid for every member of the federation. For example, if you have a union type string | number, you cannot use a method that exists only on string:
Function printId (id: number | string) {console.log (id.toUpperCase ()); / / Property 'toUpperCase' does not exist on type' string | number'. / / Property 'toUpperCase' does not exist on type' number'.}
The solution is to narrow federated types in code, just as you don't have type annotations in JavaScript. Type narrowing occurs when TypeScript can infer a more specific type from the structure of the code.
For example, TypeScript knows that using typeof on a value of type string returns the string "string":
Function printId (id: number | string) {if (typeof id = "string") {/ / In this branch, id is of type 'string' console.log (id.toUpperCase ());} else {/ / Here, id is of type' number' console.log (id);}}
To give another example, use a function such as Array.isArray:
Function welcomePeople (x: string [] | string) {if (Array.isArray (x)) {/ / Here:'x'is' string [] 'console.log ("Hello,"+ x.join (" and "));} else {/ / Here:' x'is' string' console.log (" Welcome lone traveler "+ x);}}
Note that in the else branch, we don't need to do anything special. If x is not string [], then it must be string.
Sometimes, if every member of a union type has an attribute, for example, numbers and strings have a slice method, you can use this property directly without narrowing the type:
/ / Return type is inferred as number [] | stringfunction getFirstThree (x: number [] | string) {return x.slice (0,3);} above is all the content of the article "what are the common types of TypeScript". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.