In this section, we talk about the declaration of variables. Variables can be understood literally, which is the amount that can be changed. From a programming perspective, a variable is a namespace in memory, which is mainly used to store values. We can understand it as a container for values in a program.

We know that TypeScript has a special feature that the variable is strongly typed, which means that the variable must be assigned a type when declaring the variable. This is different JavaScript JavaScript is a weakly typed language. JavaScript do not need to specify the type when declaring variables in 061265afb5e2d2.

Way of declaring variables

In JavaScript , you can use keywords var , let , const to declare variables, of course, the same can also be used in TypeScript.

The three ways of declaring variables are different, as shown below:

  • Use the var keyword to declare a variable, which acts in the function where the statement is located, and there is a variable promotion phenomenon.
  • The declaration of let var , but its scope is in the code block where the statement is located, and there is no variable promotion. Note that one of them is in the function and the other is in the code block. The code block is the code enclosed in {}
  • const is let . It can prevent the reallocation of variables. It is generally used to declare constants. The value of constants cannot be modified in the code that appears later.

Variable naming rules

Before talking about how to declare variables, let's take a look at the variable naming rules of TypeScript

  • Variable names can contain numbers, letters, underscores _ and dollar $ symbols. Others are not allowed. For example, a , abc , AA , a_ all comply with naming conventions.
  • Variable names cannot start with numbers. For example, 7a does not conform to the variable naming convention, but a7 is ok.

Use the keyword var to declare variables

First of all, in the JavaScript language, we all use the keyword var to declare variables. So why TypeScript we prefer to use let , we'll cover the following reasons.

Declaring variables in TypeScript is actually very similar to JavaScript But because one is a strongly typed language and the other is a weakly typed language, there will be some differences in the format of declaring variables between the two.

There are four ways to declare variables in TypeScript

  • The first is to declare the type and initial value of the variable. You need to add the variable : and the variable type after the variable name:
var [变量名] : [类型] = 值;

// 例如
var a : number = 1;
  • The second is to declare the type of the variable, but not assign an initial value. In this case, the value of this variable defaults to undefined :
var [变量名] : [类型];

// 例如
var a:number;
  • The third type is to declare the variable and assign the initial value, but not to declare the type. At this time, the variable type will be set to any (any type). This declaration method is similar to that in JavaScript
var [变量名] = 值;

// 例如 
var a = 1;
  • The fourth is that the variable type is not declared and no initial value is assigned. In this case, the data type of the variable is any , and the initial value is undefined :
var [变量名];

// 例如
var a;
Example:

For example, we declare 4 different variables in 4 different ways, and output their values:

// 第一种
var a:number = 100;
console.log(a);  

// 第二种
var b:string;
b = 'xkd';
console.log(b);  

// 第三种
var c = true;
console.log(c);  

// 第四种
var d;
d = [1, 2, 3];
console.log(d);  

After compiling with the tsc test.ts command, you will get the following JavaScript code:

// 第一种
var a = 100;
console.log(a);
// 第二种
var b;
b = 'xkd';
console.log(b);
// 第三种
var c = true;
console.log(c);
// 第四种
var d;
d = [1, 2, 3];
console.log(d);

Execute the code, output:

100
xkd
true
[ 1, 2, 3 ]

Note that, in the name of a variable, remember not to use name , otherwise it will and DOM the global window under Objects name properties appear the same name.

Example:

When we VSCode , if we use name as the variable name, VSCode will directly prompt an error, as shown in the following figure:

One more thing to note is that we know that TypeScript is a strongly typed language, so if we assign a type to the variable when declaring a variable, and assign the value of another type to this variable when TypeScript , the 061265afb5e71a compiler Will produce an error.

Example:

We declare a string type variable a , and then assign a numeric value to this variable:

VSCode will use a red wavy line to remind us that this is wrong. Put the mouse on the red wavy line, and the cause of the error will appear.

Type assertion

TypeScript allows variables to be changed from one type to another. TypeScript this process Type Assertion. The way to achieve this is to <> symbols and put it in front of the variable or expression.

grammar:

<类型> 值
Example:

For example, the following code:

var str1 = '1' 
var str2:number = 100;
console.log(typeof(str1));  
console.log(typeof(str2));  

var str2:number = <number> <any> str1   // 类型断言

console.log(typeof(str1));  
console.log(typeof(str2));  

Compile into JavaScript code:

var str1 = '1';
var str2 = 100;
console.log(typeof (str1)); 
console.log(typeof (str2)); 
var str2 = str1; // 类型断言
console.log(typeof (str1)); 
console.log(typeof (str2)); 

Output result:

string
number
string
string

Type assertion looks a lot like type conversion, but in fact it is not the same. General type conversion means some kind of runtime support, while type assertion is just a compile-time construct, which is a way to provide the compiler with hints on how to analyze the code. . TypeScript will assume that you have performed the necessary checks.

In addition, there is another grammatical form of type assertion. The two forms of writing are equivalent. As for which one to use is mostly a matter of personal preference.

As follows:

值 as 类型

But if we TypeScript use in JSX , it only supports this wording.

Variable scope

The scope of a variable specifies where the variable is defined, and the availability of variables in the program is determined by its scope. Variables cannot be used outside the scope.

TypeScript is divided into the following three types:

  • Global scope: Global variables are defined outside the program structure and can be used anywhere in the code.
  • Local scope: Local variables can only be accessed in the function or code block in which they are declared.
  • Class scope: It can also be called a field. A class variable is declared in a class, but outside the method of the class, the variable can be accessed through the object of the class. Class variables can also be static, and static variables can be directly accessed through the class name.
Example:

Three variables are defined in the following code, and the scope of these three variables is different:

var global_a = 1; // 全局变量

class Person{
    class_a = 2;           // 类变量
    static static_a = 3;   // 静态变量

    show():void{
        var local_a = 4;   // 局部变量,只能在定义它的函数中使用
    }
}

// 全局变量可以在全局使用
console.log("全局变量:" + global_a);

// 静态变量可以直接通过类名访问
console.log("静态变量:" + Person.static_a);

// 实例化类
var per = new Person();
// 类变量需要通过实例对象访问
console.log("实例变量:" + per.class_a);

The code of tsc test.ts compiled with JavaScript

var global_a = 1; // 全局变量
var Person = /** @class */ (function () {
    function Person() {
        this.class_a = 2; // 类变量
    }
    Person.prototype.show = function () {
        var local_a = 4; // 局部变量,只能在定义它的函数中使用
    };
    Person.static_a = 3; // 静态变量
    return Person;
}());
// 全局变量可以在全局使用
console.log("全局变量:" + global_a);
// 静态变量可以直接通过类名访问
console.log("静态变量:" + Person.static_a);
// 实例化类
var per = new Person();
// 类变量需要通过实例对象访问
console.log("实例变量:" + per.class_a);

Execute the JavaScript , output:

全局变量:1
静态变量:3
实例变量:2

First global_a is a global variable that can be used in the global range, for example, it may be Person use outside the class, in Person using the class which can also be in show use function.

And class_a is a class variable. The variables defined in the class are called class variables. We can access the class variables through the instance object of the class, such as per.class_a .

static_a is also a class variable, but this variable is static , so it is also a static variable, which can be accessed directly by the class name, such as Person.static_a .

Finally, there is the local variable local_a . The scope of this variable is only in the function in which it is located, so it can only be used in the show() function. If it is used elsewhere, an error will be reported.

Have you figured out what local variables, global variables, and class variables are now?

Hands-on practice

1. Use four different ways to declare a variable of string type and assign a value to the variable?

2. Please indicate the scope of the a , b , c , d

class Car{
    a = "red";
    run():string{
        var b = "40km/h";
        return b;
    }

    wheel(){
        var c = 4;
    }
}
var d = "jeep";

Link: https://www.9xkd.com/


知否
221 声望177 粉丝

Skrike while the iron is hot.