In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the basic uses of Typescript". Friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the basic ways to use Typescript?"
Superset is the term of set theory.
When it comes to supersets, I have to say that another subset, how to understand these two concepts, for example.
If all the elements in a set An exist in set B, then we can understand that set An is a subset of set B, whereas set B is a superset of set A.
Now we can understand that Typescript contains all the features of Javascript, which means that we can directly name the .js suffix as .ts file and run it into TypeScript's programming system.
What problem did Typescript solve?
The birth of a thing must have the value of its existence.
So what is the value of Typescript?
Before answering this question, it is necessary for us to understand the working philosophy of Typescript.
In essence, it adds a static type system to JavaScript (type analysis at compile time), emphasizing that the static type system is to distinguish it from the type checking mechanism at run time, and the code of TypeScript will eventually be compiled to JavaScript.
Let's go back to the problem itself and narrow it down a little bit. Most of the value created by Typescript is reflected at development time (compile time), not at run time, such as
Powerful editor smart tips (R & D efficiency, development experience)
Enhanced readability of code (teamwork, development experience)
Compile-time type checking (business is robust, Top10 error types in front-end projects account for 70% of low-level type errors)
Variable declaration
Basic type
Let isDone: boolean = false let num: number = 1 let str: string = 'vue3js.cn' let arr: number [] = [1,2,3] let arr2: Array = [1,2,3] / / generic array let obj: Object = {} let u: undefined = undefined; let n: null = null
Type supplement
Enumerate Enum
Use enumerated types to give a friendly name to a set of values
Enum LogLevel {info = 'info', warn =' warn', error = 'error',}
Tuple Tuple
Allows the elements of the array to be of the same type. For example, you can define a pair of tuples with values of type string and number, respectively
/ / Declare a tuple type let x: [string, number]; / / Initialize it x = ['hello', 10]; / / OK / / Initialize it incorrectly x = [10,' hello']; / / Error
Arbitrary value Any
Represents any type, usually used for uncertain content, such as from user input or a third-party code base
Let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; / / okay, definitely a boolean
Null Void
In contrast to any, it is usually used in functions to indicate that no value is returned
Function warnUser (): void {console.log ("This is my warning message");}
Interface interface
Type contract, just like we usually have to define fields in order to transfer the server interface.
The following example: point and Point types must be the same, and one more and one less is not allowed.
Interface Point {x: number y: number zoning: number readonly l: number} const point: Point = {x: 10, y: 20, z: 30, l: 40} const point2: Point = {x:'10, y: 20, z: 30, z: 40} / / Error const point3: Point = {x: 10, y: 20, z: 30} / / Error const point4: Point = {x: 10, y: 20, z: 30, l: 40, m: 50} / / Error
Optional or read-only? Indicates optional parameter, and readonly indicates read-only
Const point5: Point = {x: 10, y: 20, l: 40} / normal point5.l = 50 / / error function parameter type and return value type function sum (a: number, b: number): number {return a + b}
Use with interface
Interface Point {x: number y: number} function sum ({x, y}: Point): number {return x + y} sum / / 3 generics
The meaning of generics lies in the reusability of functions. Design principles hope that components can support not only current data types, but also future data types.
such as
According to the original design function of the business, the input parameter identity is String
Function identity (arg: String) {return arg} console.log (identity ('100'))
Business iterative process parameters need to support Number
Function identity (arg: String) {return arg} console.log (identity) / / Argument of type '100' is not assignable to parameter of type' String'.
Why not use any?
Using any will lose some information, and we are not sure what type of return value it is.
Generics guarantee that the input parameter is of the same type as the return value, which is a special variable that is only used to represent the type, not the value.
Syntax (arg:T): t, where T is a custom variable
Const hello: string = "Hello vue!" Function say (arg: t): t {return arg;} console.log (say (hello)) / / Hello vue!
Generic constraint
We used the same example and added a console, but unfortunately, we got it wrong, because generics cannot guarantee that every type has a .length property.
Const hello: string = "Hello vue!" Function say (arg: t): t {console.log (arg.length) / / Property 'length' does not exist on type' Tests. Return arg;} console.log (say (hello)) / / Hello vue!
From this, we also see a difference from any. If we want to end the battle at the constraint level, we need to define an interface to describe the constraints.
Interface Lengthwise {length: number;} function say (arg: t): t {console.log (arg.length) return arg;} console.log (say (1)) / / Argument of type'1' is not assignable to parameter of type 'Lengthwise'. Console.log (say ({value: 'hello vouchers, length: 10}) / {value:' hello vouchers, length: 10} crossover type
Cross type (Intersection Types), which combines multiple types into a single type
Interface foo {x: number} interface bar {b: number} type intersection = foo & bar const result: intersection = {x: 10, b: 20} const result1: intersection = {x: 10} / / error union type
A Union Types, indicating that a value can be one of several types. We use a vertical bar | separate each type, so number | string | boolean indicates that a value can be number, string, or boolean
Type arg = string | number | boolean const foo = (arg: arg): any = > {console.log (arg)} foo (1) foo ('2') foo (true) function overload
Function overloading (Function Overloading) allows you to create subroutines with the same name but different input and output types or different numbers, which can be simply understood as the ability of a function to perform multiple tasks.
For example, we have an add function, which can receive parameters of type string for splicing, or receive parameters of type number for addition.
Function add (arg1: string, arg2: string): string function add (arg1: number, arg2: number): number / / implement function add (arg1: t, arg2: U) {/ / We should pay attention to strictly judging whether the types of the two parameters are equal You can't simply write an arg1 + arg2 if (typeof arg1 = 'string' & & typeof arg2 =' string') {return arg1 + arg2} else if (typeof arg1 = 'number' & & typeof arg2 =' number') {return arg1 + arg2}} add (1,2) / / 3 add / /'12'. So far, I believe you have a better understanding of "what is the basic use of Typescript". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.