TypeScript basic usage
This chapter introduces some of the most basic syntax and usage of TypeScript.
The most complete tutorial: https://tut.qzxdp.cn/typescript/Online
tools: https://tools.qzxdp.cn/
type declaration
The most obvious feature of TypeScript code is the addition of type declarations for JavaScript variables.
let foo:string;
In the above example, foo
a colon is used after the variable to declare its type string
.
Type declarations are always written by adding "colon + type" after the identifier. Function parameters and return values are also declared in this way.
function toString(num:number):string {
return String(num);
}
In the above example, the type of the function toString()
parameters num
is number
. After the parentheses in the parameter list, the type of the return value is declared string
. For a more detailed introduction, see the chapter "Function".
Note that the value of the variable should be consistent with the declared type. If it is inconsistent, TypeScript will report an error.
// 报错
let foo:string = 123;
In the above example, foo
the type of the variable is string, but if the value is assigned to a numeric value 123
, TypeScript will report an error.
In addition, TypeScript stipulates that variables can only be used after being assigned a value, otherwise an error will be reported.
let x:number;
console.log(x) // 报错
In the above example, the variable x
is read without being assigned a value, resulting in an error. JavaScript allows this behavior without reporting an error, and unassigned variables will be returned undefined
.
type inference
Type declarations are not required, if not TypeScript will infer the type itself.
let foo = 123;
In the example above, the variable foo
has no type declaration, so TypeScript will infer its type. Since it is assigned a numeric value, TypeScript infers its type number
.
Later, if the variable foo
is changed to a value of another type that is inconsistent with the inferred type, TypeScript will report an error.
let foo = 123;
foo = 'hello'; // 报错
In the above example, foo
the type of the variable is inferred number
, and if it is later assigned to a string, TypeScript will report an error.
TypeScript can also infer function return values.
function toString(num:number) {
return String(num);
}
In the above example, the function toString()
does not declare the type of the return value, but TypeScript infers that the returned value is a string. Because of TypeScript's type inference, the type of a function's return value is usually omitted.
As you can see from here, the design idea of TypeScript is that type declarations are optional, you can add them or not. Even without a type declaration, it is still valid TypeScript code, but there is no guarantee that TypeScript will correctly infer the type. due to this reason. All JavaScript code is legal TypeScript code.
Another benefit of this design is that when changing a previous JavaScript project to a TypeScript project, you can gradually add types to the old code. Even if some code is not added, it will not be unable to run.
Compilation of TypeScript
The JavaScript runtime environment (browser and Node.js) does not understand TypeScript code. Therefore, in order for a TypeScript project to run, it must first be converted into JavaScript code. This code conversion process is called "compile".
TypeScript officially does not provide a running environment, only a compiler. When compiling, all type declarations and type-related code will be deleted, leaving only JavaScript code that can be run, and the running results of JavaScript will not be changed.
Therefore, TypeScript's type checking is only a compile-time type check, not a run-time type check. Once the code is compiled to JavaScript, types are no longer checked at runtime.
Values and types
Learning TypeScript requires a clear distinction between "value" and "type".
"Type" is for "value" and can be regarded as a meta-attribute of the latter. Every value has a type in TypeScript. For example, 3
is a value and its type is number
.
TypeScript code only deals with types, not values. All processing related to "value" is completed by JavaScript.
This is important to remember. In the TypeScript project, there are actually two types of codes, one is the bottom-level "value code" and the other is the upper-level "type code". The former uses JavaScript syntax, and the latter uses TypeScript's type syntax.
They can be separated. The compilation process of TypeScript actually removes all "type codes" and only retains "value codes".
When writing TypeScript projects, don't confuse which is value code and which is type code.
TypeScript Playground
The simplest way to use TypeScript is to use the online compilation page on the official website, called TypeScript Playground .
As long as you open this web page and paste the TypeScript code into the text box, it will automatically compile the JavaScript code on the current page, and you can also execute the compiled product in the browser. If an error is reported during compilation, it will also give detailed error information.
This page also has full IDE support with automatic syntax prompts. In addition, it supports saving code snippets and compiler settings as URLs and sharing them with others.
It is recommended that the examples in this book be placed on this page for viewing and compilation.
tsc compiler
The compiler officially provided by TypeScript is called tsc, which can compile TypeScript scripts into JavaScript scripts. If you want to compile TypeScript code on this machine, tsc must be installed.
By convention, TypeScript script files use .ts
suffix names, and JavaScript script files use .js
suffix names. The role of tsc is to .ts
convert scripts into .js
scripts.
Install
tsc is an npm module, install it using the following command (npm must be installed first).
$ npm install -g typescript
The above command installs tsc globally, or you can install tsc as a dependent module in the project.
After the installation is complete, check whether the installation was successful.
# 或者 tsc --version
$ tsc -v
Version 5.1.6
In the above command, -v
the or --version
parameter can output the currently installed tsc version.
help information
-h
Or --help
parameter output help information.
$ tsc -h
By default, the "--help" parameter displays only the basic available options. We can use the "-all" parameter to view complete help information.
$ tsc --all
compile script
After installing tsc, you can compile TypeScript scripts.
tsc
After the command, add the TypeScript script file to compile it into a JavaScript script.
$ tsc app.ts
The above command will generate a script file in the current directory app.js
. This script is completely the compiled JavaScript code.
tsc
The command can also compile multiple TypeScript scripts at once.
$ tsc file1.ts file2.ts file3.ts
The above command will generate three JavaScript script files file1.js
, file2.js
, in the current directory file3.js
.
tsc has many parameters that can adjust the compilation behavior.
(1)–outFile
If you want to compile multiple TypeScript scripts into one JavaScript file, use --outFile
parameters.
$ tsc file1.ts file2.ts --outFile app.js
The above command will compile the file1.ts
two file2.ts
scripts into one JavaScript file app.js
.
(2)–outDir
The compilation results are saved in the current directory by default, and --outDir
parameters can be specified to save to other directories.
$ tsc app.ts --outDir dist
The above command will dist
be generated in the subdirectory app.js
.
(3)–target
In order to ensure that the compilation results can run in various JavaScript engines, tsc will compile the TypeScript code into a very low version of JavaScript by default, that is, version 3.0 (indicated by es3
). This is usually not the desired result.
At this time, you can use --target
parameters to specify the compiled JavaScript version. It is recommended to use es2015
or update the version.
$ tsc --target es2015 app.ts
Compilation error handling
During the compilation process, if no error is reported, tsc
the command will not display anything. So, if you don't see any prompts, it means the compilation is successful.
If an error is reported during compilation, tsc
the command will display the error message, but in this case, the JavaScript script will still be compiled and generated.
For example, here is an incorrect TypeScript script app.ts
.
// app.ts
let foo:number = 123;
foo = 'abc'; // 报错
In the above example, the variable foo
is of numeric type and the value is assigned to a string. If tsc
the command is used to compile the script, an error will be reported.
$ tsc app.ts
app.ts:2:1 - error TS2322: Type 'string' is not assignable to type 'number'.
2 foo = 'abc';
~~~
Found 1 error in app.ts:2
In the above example, tsc
the command outputs an error message, indicating that the variable foo
was incorrectly assigned a string value.
In this case, the compiled product app.js
will still be generated. The following is the compiled result.
// app.js
var foo = 123;
foo = 'abc';
As you can see, despite the error, tsc still compiles TypeScript into JavaScript scripts as is.
This is because the TypeScript team believes that the role of the compiler is only to give compilation errors. As for how to deal with these errors, it is the developer's own judgment. Developers know their own code better, so no matter what, the compiled product will be generated, allowing developers to decide what to do next.
If you want to stop compilation once an error is reported and do not generate compilation products, you can use --noEmitOnError
parameters.
$ tsc --noEmitOnError app.ts
After the above command reports an error, it will not be generated app.js
.
tsc also has a --noEmit
parameter, which only checks whether the type is correct and does not generate JavaScript files.
$ tsc --noEmit app.ts
The above command only checks whether there are compilation errors and will not generate them app.js
.
For more parameters of the tsc command, see the chapter "tsc Compiler".
tsconfig.json
TypeScript allows tsc
compilation parameters to be written in configuration files tsconfig.json
. As long as there is this file in the current directory, tsc
it will be read automatically, so you don’t need to write parameters when running.
$ tsc file1.js file2.js --outFile dist/app.js
The above command is written tsconfig.json
as follows.
{
"files": ["file1.ts", "file2.ts"],
"compilerOptions": {
"outFile": "dist/app.js"
}
}
With this configuration file, tsc
you can directly call the command during compilation.
$ tsc
tsconfig.json
For a detailed introduction, see the chapter "tsconfig.json Configuration File".
ts-node module
ts-node is an unofficial npm module that can run TypeScript code directly.
When using it, you can install it globally first.
$ npm install -g ts-node
Once installed, you can run TypeScript scripts directly.
$ ts-node script.ts
The above command runs the TypeScript script script.ts
and gives the running results.
If ts-node is not installed, you can also call it through npx to run TypeScript scripts.
$ npx ts-node script.ts
In the above command, npx
ts-node will be called online and run without installation script.ts
.
If you execute the ts-node command without any parameters, it will provide a TypeScript command line REPL running environment, in which you can enter TypeScript code and execute it line by line.
$ ts-node
>
In the above example, running ts-node
the command alone will give a greater than sign. This is the REPL running environment of TypeScript. You can enter the code line by line to run.
$ ts-node
> const twice = (x:string) => x + x;
> twice('abc')
'abcabc'
>
In the above example, in the TypeScript command line REPL environment, first enter a function twice
and then call the function, and you will get the result.
To exit this REPL environment, press Ctrl + d, or enter .exit
.
If you just want to simply run the TypeScript code and see the results, ts-node is a convenient method.