TypeScript Variable Declarations
A variable is a convenient placeholder used to reference a computer memory address.
We can think of a variable as a container for storing data.
Naming rules for TypeScript variables:
-
A variable name can contain numbers and letters.
-
Except for the underscore _ and dollar $ signs, it cannot contain other special characters, including spaces.
-
A variable name cannot start with a number.
A variable must be declared before use; we can use var to declare a variable.
We can declare variables in the following four ways:
Declare a variable's type and initial value:
var [变量名] : [类型] = 值;
For example:
var uname:string = "Runoob";
Declare a variable's type but no initial value; the variable value will be set to undefined:
var [变量名] : [类型];
For example:
var uname:string;
Declare a variable with an initial value but no type; the variable can be of any type:
var [变量名] = 值;
For example:
var uname = "Runoob";
Declare a variable with no type or initial value; the type can be any type, and the default initial value is undefined:
var [变量名];
For example:
var uname;
Example
var
uname
:
string
=
"Runoob"
;
var
score1
:
number
=
50
;
var
score2
:
number
=
42.50
var
sum
=
score1
score2
console.
log
(
"Name: "
uname
)
console.
log
(
"First subject score: "
score1
)
console.
log
(
"Second subject score: "
score2
)
console.
log
(
"Total score: "
sum
)
**Note:** Do not use name as a variable name, otherwise it will conflict with the name property of the global window object in the DOM.
Compile the above code using the tsc command to get the following JavaScript code:
var
uname
=
"
Runoob
"
;
var
score1
=
50
;
var
score2
=
42.50
;
var
sum
=
score1
score2
;
console
.
log
(
"
Name:
"
uname
)
;
console
.
log
(
"
First subject score:
"
score1
)
;
console
.
log
(
"
Second subject score:
"
score2
)
;
console
.
log
(
"
Total score:
"
sum
)
;
Executing this JavaScript code produces the following output:
名字: Runoob
第一个科目成绩: 50
第二个科目成绩: 42.5
总成绩: 92.5
TypeScript enforces strong typing; assigning a different type to a variable will cause a compilation error, as in the following example:
var num:number = "hello" // 这个代码会编译错误
Type Assertion
A type assertion can be used to manually specify the type of a value, allowing a variable to change from one type to another.
Syntax format:
<类型>值
or:
值 as 类型
Example
var
str
=
'
1
'
var
str2
:
number
= <
number
< any str //str and str2 are of type string
console
.
log
(
str2
)
How TypeScript determines whether a single assertion is sufficient
When type S is a subset of type T, or type T is a subset of type S, S can be successfully asserted as T. This provides extra safety when performing type assertions; completely unfounded assertions are dangerous, and if you want to do that, you can use any.
The reason it is not calledType Conversion, is that a conversion usually implies some runtime support. However, a type assertion is purely a compile-time syntax, and it is also a way of providing the compiler with guidance on how to analyze the code.
After compilation, the above code generates the following JavaScript code:
var
str
=
'
1
'
;
var
str2
=
str
;
//
str and str2 are of type string
console
.
log
(
str2
)
;
The execution output is:
1
Type Inference
When a type is not given, the TypeScript compiler uses type inference to infer the type.
If a type cannot be inferred due to a lack of declaration, it is treated as the default dynamic any type.
var
num
=
2
;
//
Type inferred as number
console
.
log
(
"
The value of the num variable is
"
num
)
;
num
=
"
12
"
;
//
Compilation error
console
.
log
(
num
)
;
The first line declares variable num and sets its initial value to 2. Note that the variable declaration does not specify a type. Therefore, the program uses type inference to determine the variable's data type; the first assignment is 2,num setting it to the number type.
In the third line, when we assign a string-type value to the variable again, a compilation error occurs, because the variable has already been set to the number type.
error TS2322: Type '"12"' is not assignable to type 'number'.
Variable scope
Variable scope specifies where a variable is defined.
The availability of a variable in a program is determined by its scope.
TypeScript has the following types of scope:
Global scope − Global variables are defined outside the program structure and can be used anywhere in your code.
Class scope − This variable can also be called Field. A class variable is declared inside a class but outside its methods. It can be accessed through an object of the class. Class variables can also be static, and static variables can be accessed directly via the class name.
Local scope − Local variables can only be used within the block (such as a method) in which they are declared.
The following example illustrates the use of the three types of scope:
var
global_num
=
12
//
Global Variables
class
Numbers
{
num_val
=
13
;
//
Instance Variables
static
sval
=
10
;
//
Static variable
storeNum
(
)
:
void
{
var
local_num
=
14
;
//
local variables
}
}
console
.
log
(
"
Global variable:
"
global_num
)
console
.
log
(
Numbers
.
sval
)
//
Static variable
var
obj
=
new
Numbers
(
)
;
console
.
log
(
"
Instance variable:
"
obj
.
num_val
)
The above code compiled to JavaScript using the tsc command is:
var
global_num
=
12
;
//
Global Variables
var
Numbers
=
/*
- @class
*/
(
function
(
)
{
function
Numbers
(
)
{
this
.
num_val
=
13
;
//
Instance Variables
}
Numbers
.
prototype
.
storeNum
=
function
(
)
{
var
local_num
=
14
;
//
local variables
}
;
Numbers
.
sval
=
10
;
//
Static variable
return
Numbers
;
}
(
)
)
;
console
.
log
(
"
Global variable:
"
global_num
)
;
console
.
log
(
Numbers
.
sval
)
;
//
Static variable
var
obj
=
new
Numbers
(
)
;
console
.
log
(
"
Instance variable:
"
obj
.
num_val
)
;
Executing the above JavaScript code produces the following output:
全局变量为: 12 10 实例变量: 13If we call the local variable local_num outside the method, an error will be reported:
error TS2322: Could not find symbol 'local_num'.