In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you how typescript defines variables and data types. I hope you will get something after reading this article. Let's discuss it together.
one。 Variable declaration mode
1.1. Declare the format of the variable
We have emphasized many times that defining variables in TypeScript requires specifying the type of identifier.
So the complete declaration format is as follows:
Var/let/const identifier: data type = assignment
For example, we declare a message, which is written as follows:
Note: the string here is lowercase, which is different from String
String is a string type defined in TypeScript, and String is a class defined in ECMAScript.
Let message: string = "Hello World"
Message = "Hello TypeScript"; / / the correct approach
Message = 20; / / wrong approach, because message is a string type
1.2. Keyword that declares a variable
Consistent after TypeScript defines variables (identifiers) and ES6, you can use var, let, and const to define:
Var myname: string = "abc"
Let myage: number = 20
Const myheight: number = 1.88
However, we will find that there is a warning when using the var keyword:
Var keyword warning
It can be seen that the var keyword is no longer recommended in TypeScript. The main reason is the same as the difference between let and var after ES6 upgrade. Var has no block-level scope and will cause a lot of problems.
So, in later development, we mainly use let and const to define variables
1.3. Type inference of variables
In development, sometimes for convenience, we do not write the corresponding data type when declaring each variable. We prefer to use the characteristics of TypeScript itself to help us infer the corresponding variable type:
Let message = "Hello World"
We don't specify a type in the above code, but message is actually still a string type:
Assign a number to message
This is because when a variable is assigned for the first time, the type of the variable is inferred based on the type of the subsequent assignment:
The above message is because the latter assignment is a string type, so message is still a string type, although it is not clearly stated.
Let message = "Hello World"; / / string type
Let age = 20; / / number type
Let isFlag = true; / / boolean type
1.4. Declare that name reported an error
When we declare a name (and many other names) in the TypeScript file, we get an error:
Declare name error message
Main error message:
Unable to redeclare block scope variable "name"
We didn't declare name in front of us, but we said that we repeated the statement.
This is because our typescript uses DOM typings as the global running environment
So when we declare name, we have the same name as the global name property in DOM
The declared location of the name
How to solve this problem?
There are two options: remove the DOM typings environment and the declaration module
Method 1: delete the environment of DOM typings
But this approach is not suitable for us, because we still want to compile our TypeScript code under DOM
Delete DOM typing
Method 2: declare our ts file as a module
Since there is a duplicate name with the global variable, we encapsulate the script into a module. Because the module has its own scope, it will not conflict with the global variable:
In Typescript, we can use ES6's export to export an object, and the file is treated as module
Let name = "coderwhy"
Export {}
1.5. Console.log reported an error
In addition, for testing convenience, we often use console.log to test, but when we use it, we will report a warning:
Console.log warning
At this time, we can configure
Configure tslint
"no-console": false
two。 JavaScript data type
2.1. Number Typ
Numeric types are frequently used in our development. TypeScript, like JavaScript, does not distinguish between integer types (int) and floating point types (double), but is unified as number types.
/ / 1. Basic definition of numeric type
Let num = 100
Num = 20
Num = 6.66
If you have studied ES6, you should know that ES6 has added binary and octal representations, while TypeScript also supports binary, octal, and hexadecimal representations:
/ / 2. Other binary representations
Num = 100; / / Decimal
Num = 0b110; / / binary
Num = 0o555; / / Octal
Num = 0xf23; / / hexadecimal
2.2. Boolean Typ
The boolean type has only two values: true and false, which is very simple
/ / representation of boolean type
Let flag: boolean = true
Flag = false
Flag = 20 > 30
2.3. String Typ
The string type is a string type and can be indicated in single or double quotation marks:
Note: if TSLint is turned on, double quotation marks are recommended by default
/ / string type representation
Let message: string = "Hello World"
Message = 'Hello TypeScript'
ES6 template strings are also supported to concatenate variables and strings:
Const name = "why"
Const age = 18
Const height = 1.88
Const info = my name is ${name}, age is ${age}, height is ${height}
Console.log (info)
2.4. Array Typ
The definition of array types is also very simple, and there are two ways:
But TSLint will recommend that we use the above approach.
Const names1: string [] = ["why", "abc", "cba"]
Const names2: Array = ["why", "abc", "cba"]
2.5. Object Typ
The object object type can be used to describe an object:
/ / object type representation
Const myinfo: object = {
Name: "why"
Age: 20
Height: 1.88
}
But the above code sends a warning:
Warning after object definition
This is because TSLint recommends that all our key be sorted alphabetically, but this is not particularly necessary, we can still turn it off:
Turn off TSLint alphabetical sorting
"object-literal-sort-keys": false
Property is not accessible
If we access the properties in myinfo, we will find that an error is reported:
Cannot find the name property
This is because TypeScript does not know that there is an attribute of name on an object type.
But if we let it be type inferred, we can access it normally:
This is because the derived type is the following type
Type of myinfo
Another way is to define the interface that we will learn later. One of the very useful features of TypeScript is the interface interface, which we will learn in great detail later.
2.6. Symbol Typ
In ES5, if we can't add the same property name to the object, such as the following:
Const person = {
Identity: "programmer"
Identity: "teacher"
}
What we usually do is to define two different attribute names: for example, identity1 and identity2.
But we can also define the same name through symbol, because the Symbol function returns a different value:
Const S1 = Symbol ("identity")
Const S2 = Symbol ("identity")
Const person = {
}
This is one use of Symbol, and you can learn more about other uses by yourself, or we'll explain it in detail when you really need it later.
2.7. Null and undefined
In JavaScript, undefined and null are two basic data types.
In TypeScript, their respective types are undefined and null, which means that they are both actual values and their own types:
Const n: null = null
Const u: undefined = undefined
three。 TypeScript data type
TypeScript introduces many useful types based on the original JavaScript: enum enumeration type, tuple type, any type, void type, never type, and so on. "
3.1. Enum Typ
3.1.1. Basic definition of enumeration
Enumerated types are common in many languages, such as C++, Java, and so on, and they are also very easy to use, so TypeScript introduces enum types to make development more convenient and secure.
Enumerated types usually define a set of data:
Enum Direction {
EAST
WEST
NORTH
SOUTH
}
Const D1 = Direction.EAST
Const D2 = Direction.NORTH
3.1.2. Values of enumerated types
Enumerated types have their own values, such as printing the D1 and D2 above
Image11
Print D1 and D2 results
By default, the data in the enumeration starts at 0, and we can change its initialization value, such as the following code:
Enum Direction {
EAST = 10
WEST
NORTH
SOUTH
}
Const D1 = Direction.EAST
Const D2 = Direction.NORTH
Console.log (D1); / / 10
Console.log (D2); / / 12
Or you can specify all of them yourself:
Enum Direction {
EAST = 10
WEST = 20
NORTH = 30
SOUTH = 40
}
Const D1 = Direction.EAST
Const D2 = Direction.NORTH
Console.log (D1); / / 10
Console.log (D2); / / 30
We can also obtain the corresponding data name through the corresponding value:
Console.log (Direction [10]); / / EAST
Console.log (Direction [30]); / / NORTH
3.2. Tuple Typ
3.2.1. Basic use of tuple
Tuple is a tuple type, and it is also available in many languages, such as Python, Swift, and so on.
Const tInfo: [string, number, number] = ["why", 18,1.88]
Const item1 = tInfo [0]; / / why, and know that the type is string type
Const item2 = tInfo [1]; / / 18, and know that the type is number type
3.2.1. Tuple and array analogy
Beginners of tuple will find it very similar to an array.
However, the same set of data is usually defined in the array, and if the data is different, the type will be lost:
Note: I use a federation type here, which I'll talk about later
Const aInfo: Array = ["why", 18,1.88]
Const itema = aInfo [0]; / / why, but does not know whether itema is of type string or number
3.3. Any Typ
In some cases, we really can't determine the type of a variable, and maybe it will change a little, so we can use the any type (similar to the dynamic type in the Dart language).
Let a: any = "why"
A = 123
A = true
Const aArray: any [] = ["why", 18,1.88]
3.4. Void Typ
The void type is usually used when a function does not return a value:
The first thing we need to say is that functions are also typed in TypeScript.
The following function, although we do not specify its type, is derived from the type:
Const sum = (num1: number, num2: number) = > {
Return num1 + num2
}
/ / equivalent to the following
Const sum: (num1: number, num2: number) = > number = (num1: number, num2: number) = > {
Return num1 + num2
}
The type of sum function
If a function does not return a value, its return type is void
We can assign null and undefined to the void type, that is, the function can return null or undefined
Const sayHello: (name: string) = > void = (name: string) = > {
Console.log ("hello" + name)
}
3.5. Never Typ
The never type represents a type of value that never exists, which is a bit of a twist, let's put it this way:
If there is an endless loop in a function, will the function return something? No, then it is not appropriate to write the void type or any other type as the return type, so we can use the never type.
If a function throws an exception, does the function also return a value? We can also use the never type at this time.
The function of an endless loop
Function that throws an exception
After reading this article, I believe you have some understanding of "how typescript defines variables and data types". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!
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.