Chapter 1 Quick Start
Chapter 1 Quick Start
0. Introduction to TypeScript
- TypeScript is a superset of JavaScript.
- It extends JS by introducing the concept of types and adding many new features.
- TS code needs to be compiled into JS by a compiler before being executed by a JS parser.
- TS is fully compatible with JS; in other words, any JS code can be used as JS directly.
- Compared to JS, TS has static types, stricter syntax, and more powerful features; TS can perform code checks before execution, reducing the likelihood of runtime exceptions; TS code can be compiled into any version of JS code, effectively solving compatibility issues across different JS runtime environments; for the same functionality, TS code tends to be larger than JS, but due to TS's clearer code structure and more explicit variable types, TS is far superior to JS in later code maintenance.
1. Setting Up the TypeScript Development Environment
Install Node.js
Use npm to install TypeScript globally
- Open the command line
- Enter: npm i -g typescript
Create a ts file
Use tsc to compile the ts file
Open the command line
Navigate to the directory where the ts file is located
Execute the command: tsc xxx.ts
2. Basic Types
Type Declaration
Type declaration is a very important feature of TS.
Through type declaration, you can specify the type of variables (parameters, arguments) in TS.
After specifying the type, when assigning a value to a variable, the TS compiler will automatically check if the value conforms to the type declaration; if it does, it will assign it; otherwise, it will report an error.
In short, type declaration sets a type for the variable, allowing the variable to store only values of a certain type.
Syntax:
let variable: type; let variable: type = value; function fn(parameter: type, parameter: type): type { ... }
Automatic Type Inference
- TS has an automatic type inference mechanism.
- When the declaration and assignment of a variable are done simultaneously, the TS compiler will automatically infer the variable's type.
- Therefore, if your variable's declaration and assignment are done at the same time, you can omit the type declaration.
Types:
Type Example Description number 1, -33, 2.5 Any number string 'hi', "hi", hi
Any string boolean true, false Boolean value true or false Literal Itself Restricts the variable's value to that literal's value any * Any type unknown * Type-safe any void Null (undefined) No value (or undefined) never No value Cannot be any value object Any JS object array [1,2,3] Any JS array tuple [4,5] Elements, a new type in TS, fixed-length array enum enum Enum, a new type in TS number
let decimal: number = 6; let hex: number = 0xf00d; let binary: number = 0b1010; let octal: number = 0o744; let big: bigint = 100n;
boolean
let isDone: boolean = false;
string
let color: string = "blue"; color = 'red'; let fullName: string = `Bob Bobbington`; let age: number = 37; let sentence: string = `Hello, my name is ${fullName}. I'll be ${age + 1} years old next month.`;
Literal
You can also use literals to specify the type of a variable, which can determine the range of values the variable can take.
let color: 'red' | 'blue' | 'black'; let num: 1 | 2 | 3 | 4 | 5;
any
let d: any = 4; d = 'hello'; d = true;
unknown
let notSure: unknown = 4; notSure = 'hello';
void
let unusable: void = undefined;
never
function error(message: string): never { throw new Error(message); }
object (not very useful)
let obj: object = {};
array
let list: number[] = [1, 2, 3]; let list: Array<number> = [1, 2, 3];
tuple
let x: [string, number]; x = ["hello", 10];
enum
enum Color { Red, Green, Blue, } let c: Color = Color.Green; enum Color { Red = 1, Green, Blue, } let c: Color = Color.Green; enum Color { Red = 1, Green = 2, Blue = 4, } let c: Color = Color.Green;
Type Assertion
In some cases, the type of a variable is very clear to us, but the TS compiler does not know it; at this point, we can use type assertion to tell the compiler the variable's type. There are two forms of assertion:
First form
let someValue: unknown = "this is a string"; let strLength: number = (someValue as string).length;
Second form
let someValue: unknown = "this is a string"; let strLength: number = (<string>someValue).length;
3. Compiler Options
Automatic File Compilation
When compiling files, using the -w flag will cause the TS compiler to automatically monitor file changes and recompile the files when changes occur.
Example:
tsc xxx.ts -w
Automatic Compilation of the Entire Project
If you directly use the tsc command, it will automatically compile all ts files in the current project into js files.
However, the prerequisite for using the tsc command directly is to first create a ts configuration file tsconfig.json in the project root directory.
tsconfig.json is a JSON file; after adding the configuration file, you can simply use the tsc command to compile the entire project.
Configuration options:
include
Defines the directory where the files to be compiled are located.
Default value: ["**/*"]
Example:
"include":["src/**/*", "tests/**/*"]
In the above example, all files in the src and tests directories will be compiled.
exclude
Defines the directories to be excluded.
Default value: ["node_modules", "bower_components", "jspm_packages"]
Example:
"exclude": ["./src/hello/**/*"]
In the above example, files in the hello directory under src will not be compiled.
extends
Defines the configuration file to be inherited.
Example:
"extends": "./configs/base"
In the above example, the current configuration file will automatically include all configuration information from base.json in the config directory.
files
Specifies the list of files to be compiled; this is only used when there are few files to compile.
Example:
"files": [ "core.ts", "sys.ts", "types.ts", "scanner.ts", "parser.ts", "utilities.ts", "binder.ts", "checker.ts", "tsc.ts" ]
The files in the list will all be compiled by the TS compiler.
compilerOptions
Compiler options are very important and relatively complex configuration options in the configuration file.
The compilerOptions include multiple sub-options to complete the compilation configuration.
Project Options
target
Sets the target version for compiling ts code.
Optional values:
- ES3 (default), ES5, ES6/ES2015, ES7/ES2016, ES2017, ES2018, ES2019, ES2020, ESNext
Example:
"compilerOptions": { "target": "ES6" }
With the above setting, the ts code we write will be compiled into ES6 version of js code.
lib
Specifies the libraries included in the runtime environment.
Optional values:
- ES5, ES6/ES2015, ES7/ES2016, ES2017, ES2018, ES2019, ES2020, ESNext, DOM, WebWorker, ScriptHost, etc.
Example:
"compilerOptions": { "target": "ES6", "lib": ["ES6", "DOM"], "outDir": "dist", "outFile": "dist/aa.js" }
module
Sets the module system used in the compiled code.
Optional values:
- CommonJS, UMD, AMD, System, ES2020, ESNext, None
Example:
"compilerOptions": { "module": "CommonJS" }
outDir
The directory where the compiled files are located.
By default, the compiled js files will be in the same directory as the ts files; setting outDir can change the location of the compiled files.
Example:
"compilerOptions": { "outDir": "dist" }
After setting, the compiled js files will be generated in the dist directory.
outFile
Compiles all files into a single js file.
By default, all code written in the global scope will be merged into a single js file; if the module is set to None, System, or AMD, the modules will also be merged into the file.
Example:
"compilerOptions": { "outFile": "dist/app.js" }
rootDir
Specifies the root directory of the code; by default, the directory structure of the compiled files will use the longest common directory as the root directory; rootDir can be used to manually specify the root directory.
Example:
"compilerOptions": { "rootDir": "./src" }
allowJs
- Whether to compile js files.
checkJs
Whether to check js files.
Example:
"compilerOptions": { "allowJs": true, "checkJs": true }
removeComments
- Whether to remove comments.
- Default value: false
noEmit
- Whether to compile the code.
- Default value: false
sourceMap
- Whether to generate sourceMap.
- Default value: false
Strict Checks
- strict
- Enables all strict checks; the default value is true, and setting it enables all strict checks.
- alwaysStrict
- Always compiles the code in strict mode.
- noImplicitAny
- Disallows implicit any types.
- noImplicitThis
- Disallows unclear types for this.
- strictBindCallApply
- Strictly checks the parameter lists for bind, call, and apply.
- strictFunctionTypes
- Strictly checks the types of functions.
- strictNullChecks
- Strict null checks.
- strictPropertyInitialization
- Strictly checks whether properties are initialized.
- strict
Additional Checks
- noFallthroughCasesInSwitch
- Checks that switch statements contain the correct break.
- noImplicitReturns
- Checks that functions do not have implicit return values.
- noUnusedLocals
- Checks for unused local variables.
- noUnusedParameters
- Checks for unused parameters.
- noFallthroughCasesInSwitch
Advanced
- allowUnreachableCode
- Checks for unreachable code.
- Optional values:
- true, ignore unreachable code.
- false, unreachable code will cause an error.
- noEmitOnError
- Does not compile in case of errors.
- Default value: false
- allowUnreachableCode
4. Webpack
In general, during actual development, we often need to use build tools to package the code; TS can also be used in conjunction with build tools. Below, we will introduce how to use TS with build tools using webpack as an example.
Steps:
Initialize the project
- Navigate to the project root directory and execute the command
npm init -y
- Main purpose: to create a package.json file.
- Navigate to the project root directory and execute the command
Download the build tools
npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader clean-webpack-plugin
- A total of 7 packages are installed:
- webpack
- The build tool webpack.
- webpack-cli
- The command line tool for webpack.
- webpack-dev-server
- The development server for webpack.
- typescript
- The ts compiler.
- ts-loader
- The ts loader, used to compile ts files in webpack.
- html-webpack-plugin
- The html plugin in webpack, used to automatically create html files.
- clean-webpack-plugin
- The clean plugin in webpack, which clears the directory before each build.
- webpack
- A total of 7 packages are installed:
Create the webpack configuration file webpack.config.js in the root directory.
const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); module.exports = { optimization:{ minimize: false // Disable code minification, optional }, entry: "./src/index.ts", devtool: "inline-source-map", devServer: { contentBase: './dist' }, output: { path: path.resolve(__dirname, "dist"), filename: "bundle.js", environment: { arrowFunction: false // Disable webpack's arrow functions, optional } }, resolve: { extensions: [".ts", ".js"] }, module: { rules: [ { test: /\.ts$/, use: { loader: "ts-loader" }, exclude: /node_modules/ } ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ title:'TS Test' }), ] }
Create tsconfig.json in the root directory; the configuration can be adjusted as needed.
{ "compilerOptions": { "target": "ES2015", "module": "ES2015", "strict": true } }
Modify package.json to add the following configuration.
{ ...... "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack", "start": "webpack serve --open chrome.exe" }, ...... }
Create ts files under src, and execute
npm run build
in the command line to compile the code, or executenpm start
to start the development server.
5. Babel
After a series of configurations, TS and webpack have been integrated. In addition to webpack, it is often necessary to combine babel to transform the code to make it compatible with more browsers. Based on the above steps, we will introduce how to integrate babel into the project.
Install the dependencies:
npm i -D @babel/core @babel/preset-env babel-loader core-js
- A total of 4 packages are installed, namely:
- @babel/core
- The core tool of babel.
- @babel/preset-env
- The predefined environment of babel.
- @babel-loader
- The loader for babel in webpack.
- core-js
- core-js is used to enable older browsers to support new ES syntax.
- @babel/core
Modify the webpack.config.js configuration file.
...... module: { rules: [ { test: /\.ts$/, use: [ { loader: "babel-loader", options:{ presets: [ [ "@babel/preset-env", { "targets":{ "chrome": "58", "ie": "11" }, "corejs":"3", "useBuiltIns": "usage" } ] ] } }, { loader: "ts-loader", } ], exclude: /node_modules/ } ] } ......
In this way, the files compiled with ts will be processed again by babel, allowing the code to be used directly in most browsers. You can specify the browser versions to be compatible with in the targets configuration option.