当前位置:网站首页>Getting started with typescript
Getting started with typescript
2022-06-24 21:51:00 【aliven1】
Chapter one Quick start
0、TypeScript brief introduction
- TypeScript yes JavaScript Superset .
- It's right JS It has been extended , towards JS The concept of type is introduced in , And added many new features .
- TS The code needs to be compiled into JS, And then to JS The parser executes .
- TS Fully compatible with JS, In other words , Any JS Code can be used directly as JS Use .
- Compare with JS for ,TS With static types , More strict grammar , More powerful features ;TS You can check your code before it executes , Reduces the probability of runtime exceptions ;TS The code can be compiled into any version of JS Code , It can effectively solve different problems JS Compatibility of operating environment ; Same function ,TS The amount of code is greater than JS, But because of TS The code structure of is clearer , Variable types are more explicit , In later code maintenance TS But far better than JS.
1、TypeScript Development environment construction
download Node.js
- 64 position :https://nodejs.org/dist/v14.15.1/node-v14.15.1-x64.msi
- 32 position :https://nodejs.org/dist/v14.15.1/node-v14.15.1-x86.msi
install Node.js
Use npm Global installation typescript
- Go to the command line
- Input :npm i -g typescript
Create a ts file
Use tsc Yes ts File for compilation
Go to the command line
Get into ts File directory
Carry out orders :tsc xxx.ts
2、 Basic types
Type declaration
The type declaration is TS A very important feature
Type declarations allow you to specify TS Medium variable ( Parameters 、 Shape parameter ) The type of
After specifying the type , When assigning a value to a variable ,TS The compiler will automatically check whether the value conforms to the type declaration , If yes, the value is assigned , Otherwise, the report will be wrong
In short , The type declaration sets the type... For the variable , So that variables can only store certain types of values
grammar :
let Variable : type ; let Variable : type = value ; function fn( Parameters : type , Parameters : type ): type { ... }
Automatic type determination
- TS Have automatic type judgment mechanism
- When the declaration and assignment of variables are carried out at the same time ,TS The compiler automatically determines the type of the variable
- So if you declare and assign variables at the same time , You can omit the type declaration
type :
type Example describe number 1, -33, 2.5 Arbitrary number string ‘hi’, “hi”, hiAny string boolean true、false Boolean value true or false Literal Its own The value of the limiting variable is the literal value any * Any type unknown * Type safe any void Null value (undefined) No value ( or undefined) never No value Cannot be any value object {name:‘ The Monkey King ’} Any of the JS object array [1,2,3] arbitrarily JS Array tuple [4,5] Elements ,TS New type , Fixed length array enum enum{A, B} enumeration ,TS New type in 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 variable , The value range of the variable can be determined by literal quantity
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( No dice )
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;
Types of assertions
In some cases , The type of variable is very clear to us , however TS The compiler doesn't know , here , You can tell the compiler the type of a variable through type assertions , There are two forms of assertion :
The first one is
let someValue: unknown = "this is a string"; let strLength: number = (someValue as string).length;
The second kind
let someValue: unknown = "this is a string"; let strLength: number = (<string>someValue).length;
3、 Compilation options
Automatically compile files
When compiling a file , Use -w After the instruction ,TS The compiler will automatically monitor the changes of the file , And recompile the file when the file changes .
Example :
tsc xxx.ts -w
Automatically compile the entire project
If used directly tsc Instructions , You can automatically delete all items under the current project ts The file is compiled as js file .
But it can be used directly tsc The premise of the command , First create a file in the root directory of the project ts Configuration file for tsconfig.json
tsconfig.json It's a JSON file , After adding the configuration file , Just... Just tsc Command to complete the compilation of the whole project
configuration option :
include
Define the directory where you want the files to be compiled
The default value is :[“**/*”]
Example :
"include":["src/**/*", "tests/**/*"],** Represents any directory ,* Represents any fileIn the above example , all src Contents and tests All files in the directory will be compiled
exclude
Define directories that need to be excluded
The default value is :[“node_modules”, “bower_components”, “jspm_packages”]
Example :
"exclude": ["./src/hello/**/*"]In the above example ,src Next hello No files in the directory will be compiled
extends
Define the inherited configuration file
Example :
"extends": "./configs/base"In the above example , The current configuration file will automatically contain config Under the table of contents base.json All configuration information in
files
Specify the list of compiled files , It 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" ]All files in the list will be TS The compiler compiles
compilerOptions
Compilation options are very important and complex configuration options in configuration files
stay compilerOptions Contains multiple sub options , Used to complete the configuration of compilation
Project options
target
Set up ts Target version of code compilation
Optional value :
- ES3( Default )、ES5、ES6/ES2015、ES7/ES2016、ES2017、ES2018、ES2019、ES2020、ESNext
Example :
"compilerOptions": { "target": "ES6" }Set as above , What we wrote ts The code will be compiled as ES6 Version of js Code
lib
Specify the libraries included in the code run time ( Host environment )
Optional value :
- ES5、ES6/ES2015、ES7/ES2016、ES2017、ES2018、ES2019、ES2020、ESNext、DOM、WebWorker、ScriptHost …
Example :
"compilerOptions": { "target": "ES6", "lib": ["ES6", "DOM"], "outDir": "dist", "outFile": "dist/aa.js" }
module
Set the modular system used by the compiled code
Optional value :
- CommonJS、UMD、AMD、System、ES2020、ESNext、None
Example :
"compilerOptions": { "module": "CommonJS" }
outDir
The directory of the compiled file
By default , The compiled js The document will be with ts The files are located in the same directory , Set up outDir After, you can change the location of the compiled file
Example :
"compilerOptions": { "outDir": "dist" }Set the post compiled js The file will be generated to dist Catalog
outFile
Compile all the files into one js file
By default, all code written in the global scope will be merged into one js file , If module Formulated the None、System or AMD Then the modules will be merged into the file
Example :
"compilerOptions": { "outFile": "dist/app.js" }
rootDir
Specify the root directory of the code , By default, the directory structure of compiled files will take the longest public directory as the root directory , adopt rootDir You can manually specify the root directory
Example :
"compilerOptions": { "rootDir": "./src" }
allowJs
- Whether the js File compilation
checkJs
Whether the js Check the documents
Example :
"compilerOptions": { "allowJs": true, "checkJs": true }
removeComments
- Delete comment
- The default value is :false
noEmit
- Don't compile code
- The default value is :false
sourceMap
- Whether to generate sourceMap
- The default value is :false
Strictly check
- strict
- Enable all strict checks , The default value is true, After setting, it is equivalent to turning on all strict checks
- alwaysStrict
- Always compile code in strict mode
- noImplicitAny
- Prohibit implicit any type
- noImplicitThis
- Prohibit ambiguous types of this
- strictBindCallApply
- Strictly check bind、call and apply Parameter list for
- strictFunctionTypes
- Strictly check the type of function
- strictNullChecks
- Strict null check
- strictPropertyInitialization
- Strictly check whether the property is initialized
- strict
Additional checks
- noFallthroughCasesInSwitch
- Check switch The statement contains the correct break
- noImplicitReturns
- Check that the function has no implicit return value
- noUnusedLocals
- Check unused local variables
- noUnusedParameters
- Check unused parameters
- noFallthroughCasesInSwitch
senior
- allowUnreachableCode
- Check unreachable code
- Optional value :
- true, Ignore unreachable code
- false, Unreachable code will cause an error
- noEmitOnError
- Do not compile if there are errors
- The default value is :false
- allowUnreachableCode
4、webpack
Usually , In actual development, we all need to use the build tool to package the code ,TS It can also be used in conjunction with construction tools , It's down to webpack As an example, let's introduce how to use... In combination with construction tools TS.
step :
Initialize project
- Go to the project root directory , Carry out orders
npm init -y- The main role : establish package.json file
- Go to the project root directory , Carry out orders
Download the build tool
npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader clean-webpack-plugin- A total of 7 A package
- webpack
- Building tools webpack
- webpack-cli
- webpack Command line tools for
- webpack-dev-server
- webpack Development server for
- typescript
- ts compiler
- ts-loader
- ts loader , Used in webpack Chinese compiler ts file
- html-webpack-plugin
- webpack in html plug-in unit , Used to automatically create html file
- clean-webpack-plugin
- webpack Clear plug-ins in , Each build will first clear the directory
- webpack
- A total of 7 A package
Created in the root directory webpack Configuration file for webpack.config.js
const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); module.exports = { optimization:{ minimize: false // Turn off code compression , Optional }, entry: "./src/index.ts", devtool: "inline-source-map", devServer: { contentBase: './dist' }, output: { path: path.resolve(__dirname, "dist"), filename: "bundle.js", environment: { arrowFunction: false // close webpack Arrow function of , Optional } }, resolve: { extensions: [".ts", ".js"] }, module: { rules: [ { test: /\.ts$/, use: { loader: "ts-loader" }, exclude: /node_modules/ } ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ title:'TS test ' }), ] }
Created in the root directory tsconfig.json, Configuration can be based on your own needs
{ "compilerOptions": { "target": "ES2015", "module": "ES2015", "strict": true } }
modify package.json Add the following configuration
{ ... A little ... "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack", "start": "webpack serve --open chrome.exe" }, ... A little ... }
stay src Create ts file , And execute... On the command line
npm run buildCompile the code , Or performnpm startTo start the development server
5、Babel
After a series of configurations , bring TS and webpack Has been combined , except webpack, It is often necessary to combine babel To convert the code so that it can be compatible with more browsers , Based on the above steps , Use the following steps to babel Introduce into the project .
Install dependency packages :
npm i -D @babel/core @babel/preset-env babel-loader core-js- A total of 4 A package , Namely :
- @babel/core
- babel Core tools of
- @babel/preset-env
- babel Predefined environment
- @babel-loader
- babel stay webpack The loader in
- core-js
- core-js Used to make the old version of the browser support the new version ES grammar
- @babel/core
modify webpack.config.js The configuration file
... A little ... 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/ } ] } ... A little ...In this way , Use ts The compiled file will be again babel Handle , So that the code can be used directly in most browsers , You can configure options in the targets Specify the browser version to be compatible in .
边栏推荐
- TypeScript快速入门
- Make tea and talk about heroes! Leaders of Fujian Provincial Development and Reform Commission and Fujian municipal business office visited Yurun Health Division for exchange and guidance
- Analysis of tcpdump packet capturing kernel code
- [camera Foundation (I)] working principle and overall structure of camera
- Call process of package receiving function
- PKI notes
- Bld3 getting started UI
- 自己总结的wireshark抓包技巧
- leetcode_1365
- Fuzhou business office of Fujian development and Reform Commission visited the health department of Yurun university to guide and inspect the work
猜你喜欢

188. the best time to buy and sell stocks IV

平衡二叉搜索树

Blender FAQs

【论】A deep-learning model for urban traffic flow prediction with traffic events mined from twitter

(待补充)GAMES101作业7提高-实现微表面模型你需要了解的知识

Web project deployment

memcached完全剖析–1. memcached的基础

Installing Oracle without graphical interface in virtual machine centos7 (nanny level installation)

【Camera基础(一)】Camera摄像头工作原理及整机架构

【论】Deep learning in the COVID-19 epidemic: A deep model for urban traffic revitalization index
随机推荐
Memcached full profiling – 1 Fundamentals of memcached
(待补充)GAMES101作业7提高-实现微表面模型你需要了解的知识
Web project deployment
【吴恩达笔记】卷积神经网络
Tdengine can read and write through dataX
Make tea and talk about heroes! Leaders of Fujian Provincial Development and Reform Commission and Fujian municipal business office visited Yurun Health Division for exchange and guidance
滤波数据分析
Sslhandshakeexception: no subject alternative names present - sslhandshakeexception: no subject alternative names present
VSCode无网环境快速迁移开发环境(VIP典藏版)
suspense组件和异步组件
Volcano becomes spark default batch scheduler
TypeScript快速入门
Blender FAQs
福建省发改委福州市营商办莅临育润大健康事业部指导视察工作
建木持续集成平台v2.5.0发布
#国企央企结构化面试#国企就业#墨斗互动就业服务管家
Memcached comprehensive analysis – 3 Deletion mechanism and development direction of memcached
Based on asp Net development of fixed assets management system source code enterprise fixed assets management system source code
为什么生命科学企业都在陆续上云?
dp问题集