当前位置:网站首页>TS learning notes
TS learning notes
2022-07-20 22:04:00 【RedGhost117】
TS Learning notes
- Study Ts Take notes when , Emphasis on ts The basic use and difference between js Characteristics of , Practice cases encountered in the future will be added
Have to say , and Java So much alike. ... Yes Java Basic learning is not too comfortable
- Friends reading this article need to have some js Basics
List of articles
- TS Learning notes
- One . TS summary
- Two . Vscode How to write ts Code
- 3、 ... and . Basic types ( Several basic types , Other basic types expand )
- Four . Arrays and tuples
- 5、 ... and . enumeration
- 6、 ... and . any and void type
- 7、 ... and . Union type and type assertion
- 8、 ... and . Interface interface
- Nine . class class
- ( Ten ) function
- ( 11、 ... and ) Generic
One . TS summary
1. What is? TS
- TypeScript abbreviation TS
- ts yes js Superset , Finally compiled as js Code execution
- ts Expanded js The grammar of , Any existing js Programs can run on ts Environment
- ts Have a strong Type system , Strong type language
Two . Vscode How to write ts Code
1. Manually compile
- ts If you use ts Unique grammar , It needs to be manually compiled into js To run in the browser , Otherwise, you don't need to compile separately
- Compiling method :tsc+ Relative paths
tsc ./01.ts
After the html Reference compiled js that will do
- In this case ts And compiled js difference
2. Automatic compilation
- First, in the cmd Input in
tsc --init
- Generate a json file , Change the inside outDir
- After that vscode Of terminal —— Run the task —— All the tasks ——tsc monitor Turn on automatic compilation
- effect : It will be automatically generated after saving js file
3、 ... and . Basic types ( Several basic types , Other basic types expand )
- Define the way
let Variable name : type = The value of the corresponding type
- Boolean type
- Numeric type
- String type
let flag:boolean=true; // Boolean type
let num:number=1; // Numeric type
let str:string="szk";// String type
- undefined and null:
- Both mean ” empty “, But it's different
- undefined Indicates that there should be a value , But it has not been endowed
- null It means that this should be empty
- Both can be considered as subclasses of all types
let und:undefined=undefined;
let null:null=null;
// Both are also data types
let num1:number=undefined;
number=null;
Four . Arrays and tuples
1. Array
- The element type in the array is from the beginning Designated , Is the only one.
- Two ways to declare arrays
// The first way :let Variable name : type []
let arr1:number[]=[1,2,3,4,5];
// The second way : Generics let Variable name :< type >
let arr2:Array<number>=[1,2,3,4,5]
2. Tuples
- Elements in tuples can be of different types , The type and number should be declared well
// Tuples
let arr3:[string,number,boolean]=["szk",99,true];
5、 ... and . enumeration
- Every data value in an enumeration type is called an element , The value of the element is from 0 Began to increase , You can also specify values manually
- If the manually specified value is Numeric type , Then the next one is on the current basis +1, As in the example black
- If you manually specify String type , Then the following element must specify a value of string type , Otherwise, it will report a mistake
// Every data value in an enumeration type is called an element , The value of the element is from 0 Began to increase , You can also manually specify the size of the value
enum Color{
red,
white=100,
black,
pink='szk'
}
let red:Color=Color.red;
let black:Color=Color.black;
console.log(red); // The result is 0
console.log(Color.white)// The result is 100
console.log(black); // The result is 101
console.log(Color.pink);// The result is szk
console.log(Color['szk']) // The result is pink
- Get the name by value
6、 ... and . any and void type
- When you are not sure what type of data it is , And want to store any type , Just use any
let a:any = 'szk'
a=100
- The number of uncertain arrays , And data types can be used any
let arr:any[]=[100,"szk"]
- shortcoming : There will be no error message , There is no ts The advantages of
- Function has no return value , use void
function fun1():void{
console.log('123')
}
7、 ... and . Union type and type assertion
- Let the parameters passed in be of various types
- How to write it : function fun2(parms:string|number) Use " | " Separate different types
- This method is passed into , In static code, the compiler doesn't know what type you are using , There may be a mistake , It's time to Types of assertions , Tell compiler I know what type I'm using , I know what I'm doing
- Writing of type assertion :
- < type > Variable name Such as : < number > parms Just designated this place parms It's a number type
- Variable name as type Such as : parms as string
function fun2(parms:string|number):number{
// If a string comes in , Use type assertion , Tell compiler “ I know what I'm doing ”, No type error
if((<string>parms).length){
return (<string>parms).length
}else{
return (<number>parms).toString.length
}
}
8、 ... and . Interface interface
- Interface : A constraint , You can constrain the attributes that an object needs to contain
1. Interface writing
interface iPeople{
name: string,
// Property name : Attribute types
age:number
}
- In the function, the parameter can be interface The type of declaration
// Transmitted person Must satisfy iPerson Interface , Otherwise, the report will be wrong
function getPerson(person:iPerson){
console.log(person.name+"-"+person.age)
}
- Incoming person The type of attribute that must meet the requirements of the interface
let person={
name:"szk",
age:99
}
2. Read only and optional types
- In the interface, you can declare that the attribute is a read-only type or an optional type
- Read only type : Add one more readonly
- optional type : Add a after the attribute name ?
interface IPerson{
name:string,
readonly age:number, // read-only
sex?:string // Optional attribute
}
// Transmitted person Must satisfy iPerson Interface , Otherwise, the report will be wrong
function getPerson(person:IPerson){
console.log(person.name+"-"+person.age)
}
let person:IPerson={
name:"szk",
age:99
}
3. Used to constrain functions
- Define a in the interface “ Signature ”, Can be used to specify function types , Talk is talk The number of arguments passed in the function , The parameter name and return value can be constrained in advance in the interface
interface IFunction{
// Write a signature on the interface , It is the parameter transfer rule that the function implementing this interface needs to meet
(firstName:string,lastName:string):string;
}
// Implement this interface in this way ,function The following contents need to be the same as those in the interface
const fun1:IFunction=function(firstName:string,lastName:string):string{
return firstName+lastName;
}
- The whole case
(()=>{
// Declare an interface constraint of the class iPerson
interface iPerson{
name:string,
age:number
}
// Transmitted person Must satisfy iPerson Interface , Otherwise, the report will be wrong
function getPerson(person:iPerson){
console.log(person.name+"-"+person.age)
}
let person={
name:"szk",
age:99
}
getPerson(person)
})()
4. Inheritance of interfaces
- Interface by
extends
Keywords can inherit multiple other interfaces
interface ITeacher{
teach();
}
interface IBoss{
getMoney();
}
interface IPeople extends ITeacher,IBoss{
// adopt extends Keywords can inherit multiple interfaces
}
Nine . class class
- class : It can be understood as Templates , Through the template, you can Instantiate objects
1. class The composition of
- attribute : In this class “ data ”
- Constructors :new What parameters does this class need to provide to instantiate
- Method : Class provides methods
2. An example will show
// Definition Person class
class Person{
// attribute
firstName:string;
lastName:string;
// There are parametric structures
constructor(firstName:string,lastName:string){
this.firstName=firstName;
this.lastName=lastName;
}
// Method definition
speek(word:string) {
console.log(word);
}
}
//
let person=new Person("s","zk"); // adopt new The keyword has parameters to construct a person example
// A mandatory parameter type is Person Function of
function getPerson(person:Person){
console.log(person.firstName+person.lastName);
}
// Can pass “.“ Calls a method in the class
person.speek("hello");
3. Implementation interface
- Class implementation interface use
implements
keyword , The methods defined in the interface must be in Class , Otherwise, it will report a mistake
///
// An interface is defined , There is a way
interface ITeach{
teachStudent(teacher:string,studentNum:number):string
}
// use implemes Inherited this interface , We must realize the inside teachStudent Method
class School implements ITeach{
teachStudent(teacher: string, studentNum: number):string {
return (teacher+"teach"+studentNum.toString)
}
}
- When implementing an interface that inherits multiple interfaces , We should implement all the methods of the sub interface
// Inheritance of interfaces
interface ITeacher{
teach();
}
interface IBoss{
getMoney();
}
interface IPeople extends ITeacher,IBoss{
// adopt extends Keywords can inherit multiple interfaces
}
// Class implements this big interface , You need to implement all the methods of the interface inherited by the large interface
class People implements IPeople{
teach() {
}
getMoney() {
}
}
4. Class inheritance
- With inheritance , And then there is The relationship between parent and child classes
- There are things that can be inherited :
- Constructors
- Method
- attribute
class Person{
name:string;
age:number;
constructor(name:string,age:number){
this.age=age;
this.name=name;
}
sayHi(word:string):string {
console.log(word);
return word;
}
}
// Subclass Student Inherited the parent class Person
class Student extends Person{
// Use super Keyword to call the constructor of the parent class
constructor(name:string,age:number){
super(name,age)
}
// Overrides the method of the parent class
sayHi(stuId:string): string {
return stuId
//super You can call the method of the parent class
super.sayHi(' Hello ')
}
}
let person=new Person("szk",18);
person.sayHi("hello");
let student=new Student("szzk",20)
student.sayHi("hello")
5. Modifier
- Three modifiers
- public : Members can be accessed outside the class
- private: Only in the current class can access
- protected: It can only be accessed in the current class and its subclasses , Not externally
- static : Static
6. static
- use static The decoration is static
Static attribute
- use static Modify attribute variables
- There is no need to instantiate when calling , direct Class name . attribute that will do
class Person{
name:string;
age:number;
//static Decorated with static attributes
static job:string;
getJob(){
// Static attributes in the calling class use : Class name . Property
Person.job="teacher"
console.log
}
}
// External calls use static attributes : Class name . Property , Don't instantiate objects
console,log(Person.job)
Static methods
- use static Modifier name
- Call the static method through : Class name . Method name call
class Person{
name:string;
age:number;
//static Decorated with static attributes
static job:string;
constructor(name:string,age:number){
this.age=age;
this.name=name;
}
//static The decorated method is called static method
static getJob(){
// Static attributes in the calling class use : Class name . Property
Person.job="teacher"
console.log
}
}
// Call the static method through : Class name . Method name call
Person.getJbo();
7. abstract class
- Abstract class cannot be instantiated
- Abstract classes can contain
Abstract methods and abstract properties
, You can also include instance methods - Use other classes to inherit , Rewrite the abstract methods inside
abstract class Animal{
// Abstract properties
abstract name:string;
// Abstract method , There can be no concrete implementation
abstract eat();
// There can be instance methods
sayHi(){
console.log("hi")
}
}
class Cat extends Animal{
// Implement abstract properties
name: string="stichi"
// Implement abstract methods
eat() {
console.log("eat")
}
}
Similarities and differences between abstract classes and interfaces
- Abstract classes and interfaces can provide a specification
- Abstract classes can have constructors , There can be entity methods , Entity properties , And the interface doesn't have
- An abstract class is more like a template , In subclass
New content will be added , But the content in the abstract class also includes
- Interfaces are generally used only as
The abstraction of behavior , Cannot provide a template for a class
- Please refer to this article for details
( Ten ) function
1. ts How to write a function in
- The first way to write it :function Function name ( Parameters : Parameter type ,…): return type
- The second way :const Function name =function( Parameters : Parameter type ,…): return type
// The first one is
function add1(a:number,b:number):number{
return a+b;
}
add1(1,2)
// The second kind
const add2=function(a:number,b:number){
return a+b;
}
add2(2,3)
2. Optional and default parameters
- The parameter specifies a value when declared , It's the default parameter
- use
?
Decorated parameters are optional parameters - In the example badGuy use ? modification , Optional parameters , You can call below without filling
function watchJOJO(season:number=1,mainCharacter:string=" Air conditioner chengtaro ",badGuy?:string){
if(badGuy){
console.log(mainCharacter+season+badGuy)
}
else{
console.log(mainCharacter+season+" Katz, ")
}
}
watchJOJO(3," Air conditioner "," Good luck and good shadow ");
watchJOJO(3," Air conditioner ");
3. The remaining parameters
- Used for parameters with uncertain quantities
- use
...args:string[]
, And put it at the end of the parameter , To represent the remaining parameters - The remaining parameters appear in the form of an array
function restFun(a:string,b:string,...args:string[]){
console.log(a);
console.log(b);
console.log(args);
}
restFun("a","b","c",'d',"e","f")
4. function overloading
- ts Function overloading and in java There's a difference in , It's quite big
- Function overloading is The function names are the same , But the parameters received are different , Overloads called functions
- function overloading , Functions with the same name can be received in many ways , however Only one function can be finally implemented
function fun1(a:string,b:string):string
function fun1(a:number,b:number):number
function fun1(a:any,b:any):any{
return a+b.toString;
}
// All call fun1, But the accepted parameters are different
- Why not use union type ? Because the union type has if for possible input Numbers or strings There are four combinations , Complex judgments are needed , as follows
function add2(a:number|string,b:number|string){
// If it's just a union type , It requires very complicated judgments
if(typeof a==='string'&& typeof b==='string'){
return a+b
}
}
- If you use method overloading, you can limit two combinations
( 11、 ... and ) Generic
- Method , Interface , When a class is defined
You can't know the data type you need in advance , It is determined only when it is used
, This time we need to use generics - Usage mode : In the method , Interface , Add < T > , Then use T Alternative types
- Use the same method when calling T
// adopt Function name <T> This T It means generic , The following types can be used T Instead of , This type will be determined when using
// Use generics to adapt. I don't know what type to use when defining , It is only determined when it is used
function getArr<T>(value:T,count:number):T[]{
const arr:T[]=[];
for(let i=0;i<count;i++){
arr.push(value);
}
return arr;
}
// The type is determined in the same way when calling
getArr<string>("abc",10);
2. Generic classes
Set generics when defining classes
class Animal<T>{
name:T
callHim(parm:T):T{
return parm ;
}
}
let dog:Animal<string>=new Animal();
dog.callHim("hhh")
边栏推荐
- 筑波大学|奖励预测错误,而不是感官预测错误,在人类强化学习的模型选择中扮演着重要角色
- 在公司解决的问题
- 北京邮电大学|RIS辅助室内多机器人通信系统的联合深度强化学习
- Open the physical space for the construction of maker education courses
- After taking the PMP Exam, you can get the PDU for free
- MySQL Authentication ‘root‘ ‘mysql_native_password‘ failed: Reading from the stream has failed
- 谷歌请印度标注员给Reddit评论数据集打标签,错误率高达30%?
- 2022河南萌新联赛第(二)场:河南理工大学 L - HPU
- 2022 Henan Mengxin League game (2): Henan University of technology G - infinite
- 开启创客教育课程建设的实体空间
猜你喜欢
Microservice testing
模拟实现库函数strstr--查找子字符串
TS 学习笔记
DeFi 2.0的LaaS协议Elephant,或许是你熊市下为数不多的获利手段
JSON format interface test process
English grammar_ Possessive pronoun
The impact of the general trend of development in the robot era on the public
Ffmpeg audio and video capture
在idea中设置文档注释的方法(图文版)
2022 Henan Mengxin League game (2): Henan University of technology G - infinite
随机推荐
20220718 helmet, pedestrian detection, data set
使用Redis + lua脚本实现分布式限流
CLion编译和使用动态库
请问Redis 如何实现库存扣减操作和防止被超卖?
FFmpeg 视频解码
PMP practice once a day | don't get lost in the exam -7.19
Open the physical space for the construction of maker education courses
PyTorch笔记 - R-Drop、Conv2d、3x3+1x1+identity算子融合
PMP每日一练 | 考试不迷路-7.19
VS2017 30天试用结束后无法使用,登录界面卡主问题
ES6-11 学习笔记
留出300个小时,手把手教你做一个乐高潜水艇!网友看了都直呼大师之作
Jincang database kingbasees SQL language reference manual (3.8. database object, 3.9. database object name and qualifier)
mongo 索引备份
泡泡玛特7天市值蒸发210亿港元,国内卖不动,出海前途未卜
解析创客教育课程设置中的创新思维
VMware solves the problem of not recognizing USB
数据脱敏的功能与技术原理【详解】
Ffmpeg video decoding
MySQL advanced learning summary 12: 11 cases of index failure