当前位置:网站首页>Typescript learning summary
Typescript learning summary
2022-07-03 10:57:00 【@Chuan Chuan and Shan】
List of articles
One 、Typescript What is it?
1.TypeScript yes JavaScript A superset of type ( At present we are in ES5), It can be compiled into pure JavaScript.
TypeScript to JavaScript Plus an optional type system , to JavaScript After adding static types , It can advance the debugging from the running period to the coding period , Such as type checking 、 The function of cross-border inspection can really work . TypeScript The development experience of is far more than that of the past JavaScript Development experience , You don't need to run a program to fix potential bug.
Two 、TypeScript To configure
1. Install well NodeJS after , Run the terminal as an administrator , Use npm -g install ts-node typescript Command for global installation
If in VS Code In the development , Please install TSLint、TypeScript Hero、Bracket Pair Colorizer Etc
Create a new one .ts Postfix file , Write a paragraph at will JS Code , Click Run to see if the configuration is successful .
2.TypeScript Please go to Official website
3、 ... and 、let and const
Don't use var, Use let or const Declare variables , And add the type description , And the scope is block level, i.e {} As a boundary
let lang: string = 'TypeScript';// If type description is omitted ,TS Automatic inference is also possible
lang = 1010;//error! Union types can be used if necessary :let lang: number | string = 'TS';
let age: number = 89;
let age = 64;//error!
const pi: number = 3.14159;//pi It cannot be changed in the future , Similar constant
pi = 3.14;//error!
Four 、 deconstruction
1. Put the object 、 The elements in the array are split into specified variables , For ease of use
// Deconstruct arrays
let input = [89, 64, 2018, 10];
let [first, second] = input;// Pay attention to []
console.log(first); // 89
console.log(second); // 64
let [one, ...others] = input; // Remaining variables
console.log(...others);
// an
let newArr = [89, ...others, 18];
console.log(newArr);
// Deconstruction object
let o = {
a: "foo",
b: 12,
c: "bar"
};
let {a, b} = o;// Pay attention to {}, And the variable name must be consistent with the attribute name in the object
console.log(a, b);
5、 ... and 、 function
1. Use the full function type definition
// Name the function , There are complete parameters and return types . Don't have to ,TS Type inference will be done automatically, but... Is recommended !
function add(x: number, y: number): number {
return x + y;
}
// Anonymous functions
let myAdd = function(x: number, y: number): number { return x + y; };
console.log(myAdd(1, '2'));//error
console.log(myAdd(1));//error
console.log(typeof myAdd(1, 2));//number
2. Optional parameters
// Optional parameters , Must be placed after the necessary parameters
function greeting(firstName: string, lastName?: string) {
if(lastName) {
return `Hello ${firstName} ${lastName}!`;
}
return `Hello ${firstName}!`;
}
console.log(greeting('QiGe'));
console.log(greeting('QiGe', 'Wang'));
console.log(greeting('QiGe', 'Wang', 'Yong'));//error!
3. Default parameters
// Default parameters , It is not necessary to
function greeting(firstName: string, lastName = 'Wang') {
return `Hello ${firstName} ${lastName}!`;
}
console.log(greeting('QiGe'));
console.log(greeting('QiGe', 'HaHaHa'));
console.log(greeting('QiGe', 'HaHaHa', 'Yong'));//error!
4. The remaining parameters
Necessary parameters , Default and optional parameters have one thing in common : They represent a parameter . Sometimes , You want to manipulate multiple parameters at the same time , Or you don't know how many parameters will be passed in , stay TypeScript in , You can collect all the parameters into one variable
// The remaining parameters , Will be treated as an unlimited number of optional parameters . You can have none of them , You can also have any
function greeting(firstName: string, ...restName: string[]) {
return `Hello ${firstName} ${restName.join(' ')}!`;
}
console.log(greeting('Osama', 'bin', 'Muhammad', 'bin', 'Awad', 'bin', 'Laden'));
console.log(greeting('Laden'));
5. Arrow function
characteristic : Simplify function definition 、 solve this problem ( For further information, please check the document )
// No parameter , The function body code has only one line , The result of this line is the return value of the function
let greeting1 = () => `Hello TS!`;
console.log(greeting1());
// One parameter , The function body code has only one line , The result of this line is the return value of the function
let greeting2 = (name: string) => `Hello ${name}`;
console.log(greeting2('QiGe'));
// Two or more parameters , The function body code has only one line , The result of this line is the return value of the function
let add1 = (n1: number, n2: number) => n1 + n2;
console.log(add1(1, 2));
// Two or more parameters , Function body code is more than one line , You have to use {} The parcel , And explicitly give return
let add2 = (n1: number, n2: number) => {
let sum = n1 + n2;
return sum;// Change it to sum++ What is the result? ?
}
console.log(add2(1, 2));
6、 ... and 、 class class
Class is an attribute ( There's something ) And the function ( Can do ) Set , Is the generated object (Object) Or template of class instance .( Please note that , We're going to use Angular The framework uses a lot of classes )
Definition and use of classes
// Definition and use of classes
class MyInfo { //class Is the key word , Class names are all capitalized by default
name: string; // attribute
weather: string; // attribute
constructor(name: string, weather: string){ // Constructors , Generally used to initialize . without ,TS It will automatically generate a , For backup new Call... When creating a class instance .
this.name = name;
this.weather = weather;
}
printInfo(): void { // Other functions , No return value
console.log(`Hello, ${this.name}.`);
console.log(`Today is ${this.weather}.`);
}
}
let myData = new MyInfo('QiGe', 'raining'); // Use new Keywords generate objects , That is, an instance of this class
myData.printInfo();
Class properties and function access rights
The properties and functions in the class have access rights , The default is public That is, globally accessible , Next is protected It can be accessed inside the class and its subclasses , Finally private, Can only be accessed inside this class .
// Access right
class MyInfo { //class Is the key word , Class names are all capitalized by default
public name: string; //public attribute , Omission
private _weather: string; // Private property , Get used to _ Name it at the beginning
constructor(name: string, weather: string){ // Constructors , Generally used to initialize
this.name = name;
this._weather = weather;
}
printInfo(): void { // Other functions
this._test();
console.log(`Hello, ${this.name}.`);
console.log(`Today is ${this._weather}.`);
}
private _test(): void {
console.log('You can not call me outside!');
}
}
let myData = new MyInfo('QiGe', 'raining'); // Use new Keywords generate objects
console.log(myData._weather); //error!
myData._test(); //error
myData.printInfo();
Static attribute
The properties or functions in the class have static modification , Can be used directly without instantiation
// Static attribute , Built in or custom , There is no need to new You can use
console.log(Math.round(89.64)); //90
console.log(Math.pow(2, 8)); //256
class MyStaticClass {
static place = 'Earth';
static printInfo() {
console.log('We have only one Earth!');
}
}
console.log(MyStaticClass.place);
MyStaticClass.printInfo();
Inherit
Can pass extends Keyword inherits other classes , Thus becoming its subclass
class Animal {
// When the parameter passed in by the constructor is added with “ Access control characters ”, The class attribute with the same name will be declared at the same time , And the assignment
constructor(public name: string) { }
protected log(message: string) {
console.log(message);
}
move(distanceInMeters: number = 0) {
this.log(`${this.name} moved ${distanceInMeters}m.`);// Please note that name Where does it come from
this.log('==============');
}
}
class Horse extends Animal {
constructor(name: string) {
super(name); // adopt super Call the parent constructor
}
run(distanceInMeters = 50) { // Own unique function
this.log("Clop, clop...");
super.move(distanceInMeters); // adopt super Call the superclass method
}
}
class Eagle extends Animal {
constructor(name: string) { super(name); }
reborn() { // Own unique function
console.log('Reborn? It is a joke, hahaha!');
}
}
let tom: Horse = new Horse("Tommy the Palomino");
tom.run(8964);
let sam: Eagle = new Eagle("Sammy the Hawk");
sam.move(1024);//sam Of move Where does the function come from ?
sam.reborn();
边栏推荐
- 有些能力,是工作中学不来的,看看这篇超过90%同行
- 2021-09-22
- Flink < --> Introduction to JDBC +with parameter
- Large scale e-commerce project - environment construction
- 嵌入式軟件測試怎麼實現自動化測試?
- Pour vous amener dans le monde des bases de données natives du cloud
- The solution that prompts "system group policy prohibits the installation of this device" under win10 system (home version has no group policy)
- QT:QSS自定义 QTreeView实例
- QT:QSS自定义QGroupBox实例
- QT:QSS自定义 QTabWidget 和 QTabBar实例
猜你喜欢

User recommendation preference model based on attention enhanced knowledge perception
The normal one inch is 25.4 cm, and the image field is 16 cm

How to hide cvxpy warnings: warn: a- > P (column pointers) not strictly increasing, column x empty?

17K薪资要什么水平?来看看95后测试工程师的面试全过程…

Unity learning notes: online game pixel Adventure 1 learning process & error correction experience

Basic theoretical knowledge of software testing -- app testing

How to monitor the incoming and outgoing traffic of the server host?

What happened to those who focused on automated testing?

那些一门心思研究自动化测试的人,后来怎样了?

Uni app learning 1 bottom menu and parent-child components
随机推荐
Flink < --> Introduction to JDBC +with parameter
Qt:qss custom qradiobutton instance
有些能力,是工作中学不来的,看看这篇超过90%同行
Basic usage of sqlmap
QT:QSS自定义 QProgressBar实例
如何监测服务器主机的进出流量?
Qt:qss custom qstatusbar instance
嵌入式軟件測試怎麼實現自動化測試?
[untitled] numpy learning
Large scale e-commerce project - environment construction
Day 7 small exercise
【蓝桥杯选拔赛真题44】Scratch消灭骷髅军团 少儿编程scratch蓝桥杯选拔赛真题讲解
你真的需要自动化测试吗?
Leaders always entrust the work to flattering employees
QT: QSS custom qtableview instance
Buy health products for parents
What is the salary level of 17k? Let's take a look at the whole interview process of post-95 Test Engineers
snownlp情感分析
QT:QSS自定义 QRadioButton实例
Take you into the cloud native database industry, Amazon Aurora