“What will be hot and what to learn in 2022? This article is participating in the” Talk about 2022 Technology Trends “essay campaign.
preface
I wish you all a happy year of the Tiger ~!
JavaScript is a weakly typed language and many errors are discovered only at runtime, whereas TypeScript provides a static detection mechanism that helps detect errors at compile time.
As front-end engineering has evolved, TypeScript has come into its own to help teams avoid a lot of errors.
While using TypeScript increases the volume of code, it makes it more robust and maintainable. In addition, its type inference and syntax hint functions are verified, which can greatly improve the development efficiency.
For example, if you write a long variable, you either forget how to spell it or you’re afraid to make a mistake and copy and paste it, but with TypeScript you can type only one character and the whole variable will appear.
So laziness is productivity, and that’s one of the reasons I love TypeScript.
Basic types of
A variable can be declared before it is assigned. The assigned value must be the type defined when the variable is declared. Otherwise, an error will be reported
let a: number;
let b: string;
a = 3;//true
a = '3';//false
b = 'hello';//true
b = 5;//false
Copy the code
A variable can be assigned at the same time as it is declared. The assignment must be of the type defined at the time of the declaration; otherwise, an error will be reported
let c: boolean = false;
c = true;//true
c = 'hello';//false
Copy the code
If a variable is declared and assigned at the same time and no type is defined, TS can automatically type detect the variable based on the type at the time of declaration
let d = false;
d = true;//true
d = 123; //false
Copy the code
| can be used to connect multiple types (combined type), a variable’s value can be only one of the joint type
let b: 'male' | 'female';
b = 'male';//true
b = 'female';//true
b = 'hello'; //false
let c: boolean | string;
c = true;//true
c = 'aa';//true
c = 3;//false
Copy the code
When we are not sure what type a variable of a union type is, we can only access properties or methods that are common to all types of the union type:
Length is not a common property of string and number, so an error is reported.
ToString (), the common method to access string and number, is fine:
function fn(something: string | number) :number {
return something.length;//false
return something.toString();//true
}
Copy the code
When a variable of the union type is assigned, it can infer a type according to the rules of type inference:
The second line, myFavoriteNumber, is inferred to be a string, and accessing its length property is not an error.
The fourth line, myFavoriteNumber, is inferred to number and an error is reported when accessing its length property.
let myFavoriteNumber: string | number;
myFavoriteNumber = 'seven';
console.log(myFavoriteNumber.length); // true
myFavoriteNumber = 7;
console.log(myFavoriteNumber.length); // false
Copy the code
Any indicates any type. You can assign any value to a variable. If the type is set to any, TS type detection is disabled for the variable
The type can be set to any either explicitly or implicitly, only declared and not assigned, and the TS parser automatically determines that the variable is of type any
It is allowed to access any property on any value, and it is allowed to call any method. You can assume that after declaring a variable as any value, any operation on it returns the type of any value
/ / explicit any)
let d: any;
d = 10;
d = 'aa';
d = false;
/ / implicit any)
let e;
Copy the code
Unknown indicates that a value of an unknown type is actually a type-safe any
let f: unknown;
f = 'hello';
Copy the code
Variables of type any can be assigned to any variable, affecting the type detection of other variables
Unknown cannot be assigned to a variable of another type. Otherwise, an error will be reported
let a:any;
let b:string;
let c:unknown;
b = a;//true turns type-checking for b off
b = c;//false
Copy the code
You can do type checking before assigning a value of unknown to another type
let s: string;
if (typeof f === 'string') {
s = f;
}
Copy the code
A type assertion tells the parser the actual type of a variable
Two kinds of writing
/ / write one
s = f as string;
/ / write two
s = <string>f;
Copy the code
Sets the type of the return value of the function
function fn1() :string {
return 'hello';//true
return 3;//false
}
Copy the code
Void is used to denote empty. In the case of a function, a function has no return value
function fn2() :void {
return;
}
Copy the code
Never: The result is never returned
function fn3() :never {
throw new Error('Wrong');
}
Copy the code
Object represents a JS object
let h: object;
h = {};
h = function () {};
Copy the code
But everything in JS is an object, so it makes little sense to detect objects
The main purpose is to restrict properties in an object, not whether or not it is an object
{} is used to specify which attributes are contained in the object,
Property followed by? Indicates that the property is optional. [] indicates any property
[propName: string] Arbitrary attribute name any Arbitrary type
let i: { name: string; age? : number; [propName: string]: any }; i = {name: 'hzw' };
i = { name: 'hzw'.age: 13 };
i = { name: 'hzw'.sad: 'asd' };
Copy the code
Defining the function structure
Syntax :function fn(parameter 1: type, parameter 2: type…) If the parameter type is incorrect, an error will be reported if too many or too few parameters are specified
let k: (a: number, b: number) = > number;
k = (n1, n2) = > {
return n1 + n2;
};
Copy the code
String [] represents an Array of strings Array
Array
Array
let m: string[];
let n: Array<number>;
let o:Array<any>;
m = ['a'.'b'.'c'];
n = [1.2.3];
o = ['a'.1]
Copy the code
The parameters of some array methods are also limited by the types agreed upon when the array is defined: the push method only allows an argument of type number, but it passes an argument of type 8, so an error is reported.
let arr: number[] = [1.1.2.3.5];
arr.push('8');//false
Copy the code
Tuples are fixed – length arrays with too many or too few elements
However, the array method push can add elements to the tuple, called “out-of-bounds elements “, but the added elements must be the type defined in the tuple, otherwise an error is reported
let n: [string, number];
n = ['asd'.1];//true
n = ['asd'.1.'cc'];//false
n.push(1)//true
n.push("vv")//true
n.push(true)//false
Copy the code
Enum Enum types are suitable for selecting among several values
enum Gender {
Male,
Famale,
}
let o: { name: string; gender: Gender };
o = {
name: 'hzw'.gender: Gender.Male,
};
console.log(o.gender === Gender.Male); //true
Copy the code
& means at the same time
let p: { name: string } & { age: number };
p = { name: 'hzw'.age: 14 };
Copy the code
Alias of a type
To type an alias What instead of 1 | 2 | 3 | 4 | 5
var z: 1 | 2 | 3 | 4 | 5;
let l: 1 | 2 | 3 | 4 | 5;
type myType = 1 | 2 | 3 | 4 | 5;
let q: myType;
q = 1;
Copy the code
compile
Compile the file
Automatically compile a single file
The TSC command is used to edit the TS file. When compiling the file, the TS compiler automatically monitors the file changes after the -w command is used, and recompiles the file when the file changes.
Example:
tsc xxx.ts -w
Copy the code
Automatically compile the entire project
If you use the TSC directive directly, you can automatically compile all ts files under the current project into JS files.
To use the TSC command directly, you must create a tsconfig.json configuration file in the root directory of the project
Tsconfig. json is a JSON file. After adding the configuration file, you only need TSC to compile the entire project
tsc
Copy the code
Tsconfig. Json:
File configuration options
1. include
- Used to specify which directory ts files need to be compiled
- Default value:
"* * / *"
**
Represents any directory- Β
*
Represents any file
// Indicates any file in the SRC directory under the root directory
"include": [
"./src/**/*"].Copy the code
2. exclude
- Used to specify which directories
ts
The file does not need to be compiled - Default value:
["node_modules", "bower_components", "jspm_packages"]
// Does not compile any files in the test directory under the root directory SRC
"exclude": ["./src/test/**/*"].Copy the code
3. extends
- Used to define inherited configuration files
- After being imported, the current configuration file automatically contains all the configuration information in the imported file
// The current configuration file automatically contains all the configuration information in the root directory base.json
"extends": "./base.json".Copy the code
4. files
- Use to specify a list of files to be compiled. It is cumbersome to list the files one by one and is used only when there are fewer files to compile.
// Only hello.ts in 01 will be compiled
"files": ["./01/hello.ts"].Copy the code
compilerOptions
- Compile options are important and complex configuration options in configuration files
- in
compilerOptions
Contains a number of sub-options to complete the configuration of the compile
1. target
- Used to specify
TS
Compiled toES
version - Optional value:
ES3
(The default),ES5
,ES6/ES2015
,ES7/ES2016
,ES2017
,ES2018
,ES2019
,ES2020
,ESNext
(The latest version of ES)
// The ts code we wrote will be compiled into the ES6 version of js code
"compilerOptions": {
"target": "ES6"
}
Copy the code
2. module
- Used to specify the modular solution to use
- Optional value:
CommonJS
,UMD
,AMD
,System
,ES2020
,ESNext
,None
"compilerOptions": {
"module": "CommonJS"
}
Copy the code
3. lib
- Used to specify the library to be used in the project
- Optional value:
ES5
,ES6/ES2015
,ES7/ES2016
,ES2017
,ES2018
,ES2019
,ES2020
,ESNext
,DOM
,WebWorker
,ScriptHost
.
"compilerOptions": {
"lib": ["ES6"."DOM"],}Copy the code
4. outDir,rootDir
outDir
Used to specify the directory where the compiled file residesrootDir
Used to specify the root directory of the code
- By default, compiled
js
Files andts
Files in the same directory, setoutDir
You can change the location of the compiled file
"compilerOptions": {
"outDir": "./dist"."rootDir": "./src",}Copy the code
5. outFile
- Merge the compiled code into a file
- Set up the
outFile
After that, all the code in the global scope is merged into the same file
- if
module
Formulated theNone
,System
ζAMD
The modules are merged together into the file
"compilerOptions": {
"outFile": "dist/app.js"
}
Copy the code
6.allowJs
- Whether the
js
File to compile, default isfalse
7.checkJs
- Whether the inspection
js
Whether the code complies with the syntax. The default value isfalse
8.removeComments
- Whether to remove comments
false
9.noEmit
- Whether the compiled file is not generated. The default value is
false
10.noEmitOnError
- Do not generate compiled files (When something goes wrong), by default
false
"compilerOptions": {
"allowJs": true."checkJs": true."removeComments": false."noEmit": false."noEmitOnError": true
}
Copy the code
11. Double check
- strict
-
- Enable all strict checks. The default is
true
, which is equivalent to opening all the strict checks
- Enable all strict checks. The default is
- alwaysStrict
-
- Always compile your code in strict mode
- noImplicitAny
-
- Implicit is forbidden
any
type
- Implicit is forbidden
- noImplicitThis
-
- Type ambiguity is prohibited
this
- Type ambiguity is prohibited
- strictBindCallApply
-
- Strict inspection
bind
,call
εapply
Parameter list of
- Strict inspection
- strictFunctionTypes
-
- Strictly check the type of the function
- strictNullChecks
-
- Strict null-checking
- strictPropertyInitialization
-
- Strictly check that the property is initialized
12. Extra checks
- noFallthroughCasesInSwitch
-
- check
switch
The statement contains the correctbreak
- check
- noImplicitReturns
-
- Check that the function has no implicit return value
- noUnusedLocals
-
- Check for unused local variables
- noUnusedParameters
-
- Check for unused parameters
- allowUnreachableCode
-
- Check for unreachable code
- Optional value:
true
, ignore unreachable code;false
Unreachable code will cause an error
packaging
Webpack integration
Often, in real development, we need to use build tools to package code;
TS can also be used with the build tool. The following uses Webpack as an example to introduce how to use TS with the build tool.
1. Initialize the project
Go to the root directory of the project and run NPM init -y to create the package.json file
2. Download the build tool
npm i
webpack
webpack-cli
webpack-dev-server
typescript
ts-loader
clean-webpack-plugin
html-webpack-plugin
-D
Copy the code
A total of 7 packages were installed:
- webpack: Build tools
webpack
- webpack-cli:
webpack
Command line tool - webpack-dev-server:
webpack
Development server - typescript:
ts
The compiler - ts-loader:
ts
Loader, used in thewebpack
In the compilationts
file - html-webpack-plugin:
webpack
δΈhtml
Plug-in for automatic creationhtml
file - clean-webpack-plugin:
webpack
The directory is cleared first with each build
3. The configuration webpack
The configuration file webpack.config.js that creates webpack in the root directory
// Introduce a module that handles the path
const path = require('path');
// Introduce a plug-in that automatically generates HTML
const HTMLWebpackPlugin = require('html-webpack-plugin');
// Introduce a plug-in that clears the dist directory before each package
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// All webpack configuration information is written in modules.exports
module.exports = {
optimization: {minimize: false // Turn off code compression, optional
},
// Specify the entry file
entry: './src/index.ts'.// Specify the directory where the package file resides
output: {
// Specify a directory for the packaged files
path: path.resolve(__dirname, 'dist'),
// The name of the packaged file
filename: 'bundle.js'.// Disable arrow function optional
environment: {
arrowFunction: false,}},// Specify the module to use when webpack is packaged
module: {
// Specify the rules to load
rules: [{// test specifies the file in which the rule takes effect
test: /.ts$/.// The loader to use handles the TS file
use: [
'ts-loader',].// Files to be excluded
exclude: /node_modules/,}]},// Configure the WebPack plug-in
plugins: [
// Automatically generate HTML
new HTMLWebpackPlugin({
// Customize title
title: 'Custom title'.// This file is used as the template for the packaged HTML of the configuration template
template: './src/index.html',}).// Automatically delete files in dist
new CleanWebpackPlugin(),
],
// Sets which files can be imported as modules
resolve: {
extensions: ['.ts'.'.js'],}};Copy the code
4. Configure TS compilation options
Tsconfig. json is created in the root directory and can be configured according to your needs
{
"compilerOptions": {
// To specify the ES version to which TS is compiled
"target": "ES2015".// Used to specify which modular solution to use
"module": "ES2015".// All strictly checked master switches
"strict": true}}Copy the code
5. Modify package.json configuration
"scripts": {
// Package through webpack
"build": "webpack".// Start the Web server with Webpack and turn on support for hot updates using Google Chrome
"start": "webpack serve --open chrome.exe"
},
Copy the code
6. Project use
Create the ts file under SRC and run the NPM run build command line to compile the code.
Or run NPM start to start the development server;
Babel
- In addition to
webpack
And often in developmentbabel
To convert the code to make it compatible with more browsers - although
TS
Conversions are also supported at compile time, but only simple conversions are supported, for example:Promise
ηES6
Features,TS
You can’t convert it directly, so you have to use itbabel
To do the conversion;
1. Install dependency packages:
npm i -D @babel/core @babel/preset-env babel-loader core-js
Copy the code
A total of 4 packages are installed, which are:
- @babel/core:
babel
The core tools of - @babel/preset-env:
babel
Predefined environment of - @babel-loader:
babel
ε¨webpack
Loader in - core-js:
core-js
Used to make older browsers support newer versionsES
grammar
2. Modify the webpack.config.js configuration file
/ / configuration Babel
{
// Specify the loader
loader: 'babel-loader'./ / set the Babel
options: {
// Set the predefined environment
presets: [[// Specify the environment plug-in
'@babel/preset-env'.// Configuration information
{
// Specify the browser version
targets: {
chrome: '58'.ie: '11',},// Specify the corejs version
corejs: '3'.// Use corejs to represent usage on demand
useBuiltIns: 'usage',},],],},},Copy the code
This way, files compiled using TS will be processed by Babel again, making the code usable in most browsers.
Interfaces and generics
Use type declarations to describe the type of an object
type myType = {
name: string;
age: number;
};
const person1: myType = {
name: 'hzw'.age: 18};Copy the code
- Interfaces are used to define a class structure that can be used as a type declaration
- Interfaces are used to define which properties and methods should be included in a class
interface myObiect {
name: string;
age: number;
}
const person2: myObiect = {
name: 'hzw'.age: 18};Copy the code
Differences between type declarations and interfaces:
Type declarations cannot be duplicated The interface can be duplicated and the content is automatically merged
interface myObiect {
name: string;
}
interface myObiect {
age: number;
}
const person2: myObiect = {
name: 'hzw'.age: 18};Copy the code
- An interface is mainly responsible for defining the structure of a class. An interface can limit the interface of an object: an object can match an interface only if it contains all the attributes and methods defined in the interface.
- Interfaces only define structures without considering actual values;
- An interface functions like an abstract class, except that all methods and attributes in an interface have no real values. In other words, all methods in an interface are abstract.
interface myClass {
name: string;
bark(): void;
}
Copy the code
When defining a class, you can make it implement an interface using the implements keyword
class class1 implements myClass {
name: string;
constructor(name: string) {
this.name = name;
}
bark() {
console.log('Want want Want'); }}Copy the code
Use an interface to define the type of a function
interface ISum {
(x: number, y: number): number;
}
let add: ISum = (x: number, y: number): number= > {
return x + y;
};
Copy the code
When defining a function or class, generics can be useful in cases where the exact type to be used is uncertain (the types of return values, parameters, and attributes are uncertain).
For example, the test function has an indeterminate parameter type, but if it does, it returns the same type as the parameter.
We use any for both the argument and the return value because the type is uncertain, but this is clearly not appropriate:
Using any turns off type checking for TS, and does not indicate that the parameter and return value are of the same type.
function test(arg: any) :any{
return arg;
}
Copy the code
Generic function
function test<T> (arg: T) :T{
return arg;
}
Copy the code
Here
is generic, so how to use the above function?
Method 1 (direct use) :
When used, you can pass arguments directly and the type will be inferred automatically by TS, but sometimes the compiler cannot infer automatically
test(10)
Copy the code
Method 2 (Specify type) :
You can also specify generics manually after a function;
test<number>(10)
Copy the code
Function to declare more than one generic type
Multiple generics can be specified at the same time, separated by commas
function test<T.K> (a: T, b: K) :K{
return b;
}
test<number, string>(10."hello");
Copy the code
A generic class
Classes can also use generics:
class MyClass<T>{
prop: T;
constructor(prop: T){
this.prop = prop; }}Copy the code
Generic inheritance
You can also constrain the scope of generics
T extends MyInter means that T must be a subclass of MyInter. It does not have to be an interface class as well as an abstract class.
interface MyInter{
length: number;
}
function test<T extends MyInter> (arg: T) :number{
return arg.length;
}
Copy the code
object-oriented
Define the class
- use
class
Keyword to define a class
class Person {}
Copy the code
- Defining instance properties requires access through the instance of the object
class Person {
name: String = 'hzw';
age: number = 18;
}
const hzw = new Person();
console.log(hzw.name);//hzw
console.log(hzw.age);18
Copy the code
- use
static
The keyword defines static properties accessed through the class
class Person {
static age: number = 20;
}
console.log(Person.age);/ / 20
Copy the code
- use
readonly
The keyword defines read-only attributes - You can use both
static
εreadonly
The keyword defines the static read-only property,static
Only in thereadonly
In front of the
class Person {
readonly color: string = 'red';
static readonly height: string = '50px';
}
Copy the code
- Defining instance methods need to be accessed through an instance of an object
class Person {
sayHello(): void {
console.log('hello'); }}const hzw = new Person();
hzw.sayHello();//hello
Copy the code
- use
static
The keyword defines static methods accessed through the class
class Person {
static sayHello(): void {
console.log('hello,static');
}
}
Person.sayHello();//hello,static
Copy the code
The constructor
- The constructor is called when the object is created
class Dog {
constructor() {
console.log("Constructor called.")}}const dog1 = new Dog();// The constructor is called
Copy the code
- In the constructor, you can pass
this
Add attributes to the newly created object
class Dog {
name: String;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age; }}Copy the code
- In the instance method,
this
Represents the current instance, which can be passed in the instance methodthis
Represents the object on which the method is currently called
class Dog {
name: String;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
bark(): void {
This can be used in instance methods to represent the object on which the method is currently called
console.log(this); }}const dog1 = new Dog('black'.3);
dog1.bark();// Dog: Dog {name: "Dog ", age: 3}
Copy the code
inheritance
Inheritance makes it possible to write code common to multiple classes in a single parent class so that all subclasses have properties in the parent class at the same time, only once
- Define a class that represents an animal
Animal
class Animal {
name: String;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
bark(): void {
console.log('The animal is calling); }}Copy the code
- Define a class that represents a dog
Dog
- make
Dog
Class inheritanceAnimal
η±» - At this time
Animal
It’s called the parent class,Dog
It’s called a subclass - Using inheritance, subclasses have all the attributes and methods of their parent class
class Dog extends Animal {}const dog = new Dog('prosperous wealth'.3);
console.log(dog);// Dog {name: "Dog ", age: 3}
dog.bark();// The animal is crying
Copy the code
- Define a class that represents a cat
Cat
- make
Cat
Class inheritanceAnimal
η±»
class Cat extends Animal {}const cat = new Cat('white'.4);
console.log(cat);// CatΒ {name: "ε°η½", age: 4}
cat.bark();// The animal is crying
Copy the code
Subclasses can add their own unique properties and methods
class Dog extends Animal {
run() {
console.log(`The ${this.name}In the run ~ ~ ~ `); }}const dog = new Dog('prosperous wealth'.3);
dog.run();// Fortune is running ~~~
Copy the code
rewrite
If a subclass adds the same method as the parent class, the subclass method overrides the parent class, which is called method override
class Dog extends Animal {
bark(): void {
console.log('Want want Want'); }}const dog = new Dog('prosperous wealth'.3);
dog.bark();/ / want want
Copy the code
super
In a class method,super represents the parent of the current class, and you can use super in subclasses to complete the reference to the parent
class Animal {
name: String;
constructor(name: string) {
this.name = name;
}
bark(): void {
console.log('The animal is calling); }}// In a class method, super represents the parent of the current class
class Dog extends Animal {
bark() {
super.bark(); }}const dog = new Dog('prosperous wealth');
dog.bark();// The animal is crying
Copy the code
When a subclass inherits a parent class, it must call the constructor of the parent class if the subclass also defines a constructor!
// In a class method, super represents the parent of the current class
class Dog extends Animal {
age: number;
constructor(name: string, age: number) {
// Call the parent constructor
super(name);
this.age = age; }}Copy the code
Attribute modifier
Abstract Class
- use
abstract
Classes that begin are called abstract classes - Abstract classes are not much different from other classes except that they cannot be used to create objects
- Abstract classes are classes that are designed to be inherited by other classes. They can only be inherited by other classes and cannot be used to create instances
- Abstract methods can be added to an abstract class
- use
abstract
An abstract method has no body and can only be defined in an abstract class. When inheriting an abstract class, the abstract method must be overridden or an error will be reported
abstract class Animal {
name: String;
constructor(name: string) {
this.name = name;
}
abstract bark(): void;
}
class Dog extends Animal {
bark() {
console.log('Want want Want'); }}Copy the code
Attribute modifier
By default, the properties of an object can be modified at will. To ensure data security, the permission of the properties can be set in TS
TS attributes have three modifiers:
public
(default), which can be modified in classes, subclasses, and objectsprotected
Can be modified in a class or subclassprivate
, can be modified in the class
public
class Person{
public name: string; // Write or write nothing is public
public age: number;
constructor(name: string, age: number){
this.name = name; // Can be changed in the class
this.age = age;
}
sayHello(){
console.log('Hello, I amThe ${this.name}`); }}class Employee extends Person{
constructor(name: string, age: number){
super(name, age);
this.name = name; // Subclasses can be modified}}const p = new Person(Sun Wukong.18);
p.name = 'Pig Eight Quit';// Can be modified by object
Copy the code
protected
class Person{
protected name: string;
protected age: number;
constructor(name: string, age: number){
this.name = name; // It can be modified
this.age = age;
}
sayHello(){
console.log('Hello, I amThe ${this.name}`); }}class Employee extends Person{
constructor(name: string, age: number){
super(name, age);
this.name = name; // Subclasses can be modified}}const p = new Person(Sun Wukong.18);
p.name = 'Pig Eight Quit';// Cannot be modified
//Property 'name' is protected and only accessible within class 'Person' and its subclasses.
Copy the code
private
class Person{
private name: string;
private age: number;
constructor(name: string, age: number){
this.name = name; // It can be modified
this.age = age;
}
sayHello(){
console.log('Hello, I amThe ${this.name}`); }}class Employee extends Person{
constructor(name: string, age: number){
super(name, age);
this.name = name; // Cannot be modified in subclasses
//Property 'name' is private and only accessible within class 'Person'.}}const p = new Person(Sun Wukong.18);
p.name = 'Pig Eight Quit';// Cannot be modified
//Property 'name' is private and only accessible within class 'Person'.
Copy the code
Attribute accessor
- For properties that do not want to be arbitrarily modified, you can set them to
private
, directly set it toprivate
Properties in the object can no longer be modified - We can define a set of methods in a class that read and set properties, called accessors for properties
- The method that reads the property is called
setter
Method, the method that sets the property is calledgetter
methods
class Person{
private _name: string;
constructor(name: string){
this._name = name;
}
/ / get the property name
get name() {return this._name;
}
/ / set the attribute name
set name(name: string) {this._name = name; }}const p1 = new Person(Sun Wukong);
// The name property is actually read by calling the getter method
console.log(p1.name);
// Actually modify the name property by calling setter methods
p1.name = 'Pig Eight Quit';
Copy the code
shorthand
- Adding modifiers to parameters serves the purpose of shorthand
- No statement
name:string
- Not in the constructor
this.name=name
class Person{
constructor(public name: string){}}/ / equivalent to the
class Person {
name: string;
constructor(name: string) {
this.name = name; }}Copy the code
After the language
At this point, you are ready to use TS for initial development. But for TS, mastering this is not enough.
I would like to recommend two websites for learning TS.
ππ TypeScript tutorial
ππ In-depth understanding of TypeScript