Basic data types of Typescript (1)

The latest ECMAScript standard defines 8 data types:

  • 7 primitive types:
    • Boolean
    • Null
    • Undefined
    • Number
    • Bigint
    • String
    • Symbol
  • and Object

All types except Object are immutable (the value itself cannot be changed) . For example, unlike C, strings in JavaScript are immutable (Annotation: For example, operations on strings in JavaScript must return a new string, the original string has not been altered). We call these types of values ​​"raw values".

So let's experiment and define the data type in the ts file.

First test the boolean data:

When we define variables in ts, we use colons to assign values

Then we define a value of Boolean type and assign a number to it. At this time, we can see that ts automatically prompts and reports an error , which is one of the obvious differences between ts and js.

Let's go on to define other types of data

When we declare a commonly used variable name, an error will be prompted

 How to solve Cannot redeclare block scope variable 'name'

1. First of all, we should analyze the reasons

There are no other files in this folder, not to mention the fact that the variable name has already been defined. How did this error appear? It is very confusing.

After consulting the data, I found that there will be such a situation in ts:

In the default state, typescriptit will be DOM typingsused as the global operating environment, so when we declare name, DOMand the propertywindow under the global object in has the same name. nameTherefore, an error of Unable to. .

2. Solution

Method one:

Change the operating environment  DOM typings to another operating environment. We can  tsconfig.json make a statement in the compilerOptions in:

    "lib": [
      "es2015"
    ], 

 After saving, the error message disappears.

 Law 2:

Since it has the same name as the global variable, we encapsulate the script into a module ( module ). module With its own scope, it will naturally not conflict with variables in the global scope.

In Typescript, as long as there are import or export keywords in the file, it can be regarded as a module even without a return value

 After knowing this principle, we can add export:{} in the last line of the ts file .

After the addition, we can see that when the corresponding js file is compiled, the code compiled into the commonjs module will be automatically added

The principle is: we can see in tsconfig.js, the configured module: commonjs. It means that the compiled result uses the commonjs standard. Refer to the blog for specific principles: TS Learning (6): Modular use of TS

 In the end, after adding a line of export, the name will not report an error.

Define primitive data types:

// Boolean
let flag: boolean = false
// Number
let age: number = 10
// String
let name: string = 'suohhh'
let msg: string = `hello,${name}` //模板字符串
// Null
let u: null
// Undefined
let n: undefined
/**
 * 注意:undefined和null是所有类型的子类型
 * 也就是说undefined类型的变量可以赋值给number类型的变量
 * */
let num: number = undefined

export {
};

Note: If the variable declaration and assignment are performed at the same time, TS can automatically perform type detection on the variable. For example, let flag: boolean = false can be directly written as let flag = false, and there is no need to define the type.

At this time, someone asked, isn't it going back to the original way of writing js? Isn't this kind of type definition a bit tasteless?

Answer: In fact, the type that causes us great trouble is often not a variable, but a function.

for example:

For example, the following summation function, in js, the function does not consider the type and number of parameters, then when we pass the correct number type, we can get a correct answer, then when we pass a string, the second will appear As a result, the strings are concatenated, and no error will be reported in js at this time, which may lead to a series of errors, and it is not easy to troubleshoot.

Of course, with ts, this kind of problem is basically not a problem. Therefore, the type definition restriction of ts is mainly aimed at the strictness of parameters or return values ​​in functions.

 Modification: Restrict the parameters by type. At this time, the string will become popular, which is convenient for us to pre-process

Return values ​​can also be typed:

 

Define a union data type: 

Use symbols or | to limit variables to multiple types of declarations

Here comes the problem. What should we do if we are defining unknown user input and cannot determine what data type it is? At this time, a data type called Any   comes to the rescue.

Define any data type

Literally, it means to represent any, allowing assignment to any type,

After a variable is set to any, it is equivalent to turning off TS type detection for the variable.

// Any --显式any
let notSure: any = 4
notSure = 'string'
notSure = true

//当我们不设置类型,ts会自动检测为any类型
let d; //d为any类型 --隐式any

 Note: If you know the type clearly, try not to use any type, because this type can call properties and methods arbitrarily without reporting an error, which is very likely to cause problems, and the function of type checking will be lost.

Define the unknown data type

unknown represents a value of unknown type

What is the difference with any?

Looking at the definition below, it seems that there is no difference, and various data types can be defined

Below we respectively define a d as any type, and e as unknown type

 the difference:

Define a string type s, when we assign any type d to s, no error will be reported.

When assigning the unknown type e to s, an error will be reported

 Summarize:

         unknown is actually a type-safe any

         A variable of unknown type cannot be directly assigned to a variable 

So what if we just want to assign the unknown type of data to another variable?

Two ways:

 (1) Do a type check and tell ts to assign a value when I am of string type

 (2) Type assertion, which can be used to tell the parser the actual type of the variable

        Syntax: variable as type or <type> variable 

 void and never data types

Settings for function return type

For example, if a function has no return value, void is used to indicate empty:

At this time, if you write a return value again, an error will be reported. You can write a single return; or return null; return undefined;

 never means that the result will never be returned, even empty

 For example, to throw an error

To sum up, the first eight types have been described, and the following article will explain the last three data types in detail:

Note: The literal type is equivalent to a constant, which cannot be changed after a value is defined.

Guess you like

Origin blog.csdn.net/qq_41579104/article/details/129064368