当前位置:网站首页>Typescript basic learning notes
Typescript basic learning notes
2022-07-21 19:45:00 【jason_ renyu】
ts Study notes
The following is learning ts In process notes , For what you think you need to keep in mind , Sort it out again so that you can review the old and know the new , It is also helpful if you are lucky enough to be read by any reader , I'm very glad .
As the personal study notes are below , There is not much basic knowledge , If you need friends, you can go to TypeScript Learn from the official website , Here I recommend Ruan Yifeng 《TypeScript Introductory tutorial 》
《TypeScript Introductory tutorial 》
Shifu leads people in the door to practice , After reading the basic feeling, the research is thorough , Then I went to the project experience, and the effect was very good .
ts The definition of
ts The official definition is Typed JavaScript at Any Scale. ( Added type system JavaScript, Applicable to projects of any scale ).
ts Characteristics of
- TypeScript The type system is added JavaScript, Applicable to projects of any scale ;
- TypeScript It's a static type 、 Weakly typed languages ;
- TypeScript It's fully compatible JavaScript Of , It will not be modified JavaScript Runtime features ;
- TypeScript Can be compiled as JavaScript, And then run it in the browser 、Node.js Wait for anything to work JavaScript In the environment of ;
- TypeScript There are many compilation options , The severity of the type check is up to you ;
- TypeScript You can talk to JavaScript coexistence , It means JavaScript Projects can gradually migrate to TypeScript;
- TypeScript Enhanced editor (IDE) The function of , Provides code completion 、 Interface tips 、 Jump to definition 、 Code refactoring, etc ;
- TypeScript Have an active community , Most commonly used third-party libraries provide type declarations ;
- TypeScript Synchronous development with standards , Compound the latest ECMAScript standard
TypeScript Command tools and installation methods
install
npm install -g typescript
# or
yarn add global typescript
compile TypeScript file , for example : hello.ts
tsc hello.ts
# If you want to see the running results inside , You can use node Run the generated js file , Such as
node hello.js
Static type
Static and dynamic types , Dynamic types will throw out type errors at runtime ,
Static types throw syntax errors when compiling , When the project runs, it doesn't exist ,
TypeScript It belongs to static type , It needs to be compiled into JavaScript
Type inference
When initializing to define variable types , Without assignment , The default type is any
When there is assignment, the type of assignment is the type of current variable
let c = 12; // Equivalent to let c:number = 12;
null and undefined It is a subclass of all types , Can be assigned to other types
let c = 12;
c = null;
c = undefined;
Read-only property
The constraint of the read-only attribute lies in the first assignment to the formation , Not the first time you assign a read-only property
Example :
interface Person {
readonly city?:string,
name?:string,
readonly [propName:string]:string
}
// The constraint of the read-only attribute lies in the first assignment to the formation , Not the first time you assign a read-only property
const p1:Person = {
city: 'China',
name: 'zhangsan',
age: '21'
}
// If you assign a value to the read-only attribute later ,ts Error will be reported at compile time
// Such as
// p1.city = '12';
Like the following, when assigning a value to a row for the first time, it is empty , If you assign a value to the read-only attribute later, the compilation will report an error
const p2:Person = {
};
// Non read only normal
p2.name = '12';
// Read only error
// p2.city = '12';
enumeration
External enumeration declare The defined type will only be used for compile time checks , The compilation result will be deleted
declare enum Directions {
Up, Down, Right, Left, Middle}
Changshu enumeration , Deleted during compilation , Cannot contain calculated members
const enum Month {
One, Two, Three}
abstract class
abstract class Instance is not allowed
Such as :
// abstract class key word abstract
abstract class Animal {
public name;
private age = 81;
protected readonly isLeave = false;
public constructor(name, age){
this.name = name;
this.age = age;
}
public getAge(){
return this.age;
}
}
// An error will be reported in the instance , Such as
// const a = new Animal(' Easy to meet ', '80');
class (class) Interface with (interface) The difference between
In general , One class can only inherit from another class , Sometimes there are some common characteristics between different kinds of people ,
At this time, these features can be extracted into interfaces (interface), With extension (implements) Keyword to implement ,
This feature greatly improves the flexibility of object-oriented .
example : A door is a class , Security door is a subclass of door . If the security door has an alarm function , We can simply give the security door
Add an alarm method . At this time, if another class , vehicle ; It also has the function of alarm , You can consider extracting the alarm ,
As an interface , Security door and car to achieve it .
Code example :
// a burglar alarm
interface Alarm {
// Alarm method
alert: () => void;
}
// The lamp
interface Light {
lightOn: () => void;
lightOff: () => void;
}
// ----- door General categories ----
class Door {
// Door material
materialType: string;
constructor(materialType: string){
this.materialType = materialType;
}
}
// anti-theft door
class SecurityDoor extends Door implements Alarm,Light{
// brand
brand:string;
constructor(materialType: string, brand: string){
super(materialType);
this.brand = brand;
}
alert(){
console.log(' sound of dripping water : There is an unknown object knocking at the door ');
}
// turn on the light
lightOn(){
console.log(' The light is on ')
}
// Turn off the lights
lightOff() {
console.log(' The light is off ')
}
// Declare defining properties and using memory get set It's the same , And there can only be one group
// set brand(value:string){
// console.log(' Set brand ', brand);
// }
// get brand():string {
// return ' You don't need to look at the brand '
// }
}
// ---- vehicle class -----
class Car implements Alarm {
brand: string;
constructor(brand:string){
this.brand = brand;
}
alert(){
console.log(' sound of dripping water , Someone came to steal the car ');
}
}
Interface inheritance
Except for class inheritance , There is also interface inheritance
// Alarm lamp interface
interface AlarmLight extends Alarm, Light{
brand: string;
}
// Police cars
class PoliceCar implements AlarmLight {
brand:string;
constructor(brand: string);
alert(){
console.log(' sound of dripping water : There is an unknown object knocking at the door ');
}
// turn on the light
lightOn(){
console.log(' The light is on ')
}
// Turn off the lights
lightOff() {
console.log(' The light is off ')
}
}
Interface inheritance classes are in addition to constructors constructor Is not included , static state (static) Attribute or static (static) Methods are also not included
Generic
Generics are defining functions 、 Interface or class , Do not specify specific types in advance , When using, we can formulate a feature of the type
Assertion
Assertions are just confusing TS Validation of the , No error is reported during compilation , It can't check program errors
Assertions can assert any type as any, Can also be any Assertion is a concrete type
That's all for the above , It may be updated later , You can keep paying attention to
边栏推荐
- What is the difference between the tag attribute href of a reference URL and Src?
- ENS阅读笔记
- 45. Record the training process of orienmask and the process of deploying Yunshi technology depth camera
- Verilog grammar basics HDL bits training 03
- Kubernetes technology and Architecture (V)
- 技術帖 | A40i最常見的3種網卡軟件問題,為你逐一分析
- 好消息!PMP项目管理证书列入急需紧缺专业人才人员
- MySQL (2)
- 从平面设计转行软件测试,喜提11K+13薪,回头看看我很幸运
- Classic examples of C language: 21-30 examples: insertion sort, Hill sort 1, quick sort, Hill sort 2, recursion, completion, Fibonacci sequence, common divisor and common multiple, judging the number
猜你喜欢
26. GD32F103C8T6入门教程--正交编码器的使用
2022全网最火免费中文版-《深度学习在图像处理中的应用教程》免费分享
Classic examples of C language: 21-30 examples: insertion sort, Hill sort 1, quick sort, Hill sort 2, recursion, completion, Fibonacci sequence, common divisor and common multiple, judging the number
Momenta“飞轮式L4”接受夜间长尾场景「像素级」挑战,表现堪比老司机
Preparation of hemoglobin albumin nanoparticles encapsulated by Lumbrokinase albumin nanoparticles / erythrocyte membrane
Technical post | the three most common network card software problems of a40i are analyzed for you one by one
NFS share
C language learning
Bram for FPGA logic resource evaluation (taking Xilinx as an example)
从平面设计转行软件测试,喜提11K+13薪,回头看看我很幸运
随机推荐
解决报错:Uncaught TypeError: Cannot read properties of undefined (reading ‘install‘)
技术帖 | A40i最常见的3种网卡软件问题,为你逐一分析
【C 练习】宏实现交换数字二进制奇偶位
hot wire! The PMP project management certificate is listed in the urgently needed professional personnel
引用URL的标签属性href与src的区别是什么?
项目管理成熟度模型及项目量化管理
Flexible array of dynamic memory management 2
动作活体检测能力,构建安全可靠的支付级“刷脸”体验
sort内部实现原理
笔试强训第20天
Harbor scanner from principle to construction
【transformer】ViT
26. GD32F103C8T6入门教程--正交编码器的使用
OSPF Foundation
电磁场与电磁波实验二 熟悉Matlab PDEtool在二维电磁问题的应用
Integrated design of signal processing system - minimum order IIR digital high pass filter
What is the difference between the tag attribute href of a reference URL and Src?
Deep learning - (6) pytorch freezes the parameters of some layers
[C language] detailed explanation of file related functions
Project Management Maturity Model and project quantitative management