Preface
What is TypeScript?
develop writing habits together! This is the 21st day of my participation in the "Nuggets Day New Program · April Update Challenge". Click to view the event details.
typeScript, referred to as ts, is a static programming language developed by Microsoft . It is a superset of JavaScript. So what's special about it?
- Simply put, some js have ts, and all js code can be run in ts.
- ts supports type support, ts = type + JavaScript.
So what is the difference between ts and js?
JavaScript belongs to a dynamic programming language, while ts belongs to a static programming language.
- js: Execute while explaining, only when running can you find
- ts: compile first and then execute, and you will find errors when writing (ts cannot be executed directly, you need to compile to js first)
ts fully supports js, and you can directly convert
. Simple to understand
JS. There are, TS, and JS does not, and TS also has. After all, TS is a superset of JS. Disadvantages of
TS:
- cannot be understood by the browser and needs to be compiled into JS
- . There is a learning cost. If we are used to writing JS, it takes time to understand it to get started. Moreover, there are some concepts in TS, such as generics.
What is type annotation?
is to add type constraints to variables. can display unexpected behaviors in the code marking, thereby reducing the possibility of errors Syntax:
let Variable name: Type = initial value let age: number = 18
What are the benefits of writing like this? The type of data is better specified and unnecessary errors are avoided. If you accidentally write it wrong, he will directly prompt you for a type error. Isn't it very considerate?
For example:
let a:number = '1'
: number in the code is type annotation .
It is time to introduce the basic data type of ts
// string let str: string = "Domesy"// Number let num: number = 7// boolean let bool: boolean = true//symbollet sym: symbol = symbol(); //bigintlet big: bigint = 10n//nulllet nu: null = null//undefinedlet un: undefined = undefined
need to be noted:
- null and undefined Once the two types are assigned, they cannot be assigned to any other types
- symbol is unique. Suppose that another sym1 is defined, then sym === sym1 is false
Reference type
Array
Two ways:
- Type name + []
- Array data type
let arr1: number[] = [1, 2, 3]let arr2: Arraynumber = [1, 2, 3]let arr2: Arraynumber = [1, 2, 3]let arr2: Arraynumber = [1, 2, 3]let arr2: Arraynumber = [1, 2, 3]let arr2: Arraynumber = [1, 2, '3'] // error //If you want to be a numeric type or string type, you need to use |let arr3: Arraynumber | string = [1, 2, '3'] //ok
Tuple(tuple)
Tuple It can be said to be a special case of Array. For the above arr3, we see that its type can be string or number, but there are no specific restrictions on each element.
Then the function of Tuple is to limit the type of element and limits the array of . At the same time, the concept value of Tuple exists in TS, which does not exist on JS
There is a problem here: in TS, it allows amplification of Tuple (that is, the push method is allowed), but
let is not allowed on access t: [number, string] = [1, '2'] // oklet t1: [number, string] = [1, 3] // errorlet t2: [number, string] = [1] // errorlet t3: [number, string] = [1, '1', true] // errorlet t5: [number, string] = [1, '2'] // okt.push(2)console.log(t) // [1, '2', 2]let a =t[0] // oklet b = t[1] // oklet c = t[2] // error
also has object and definition function;
Yuan Ancestor's Problem
let aaa: [string, number] = ['aaa', 5];// There will be no error when adding aaa.push(6);// The entire Yuanzu will not report an error console.log(aaa); // ['aaa',5,6];// An error console.log(aaa[2]); // error
What is the function type interface
- Constrain the parameters and return values passed by the method
// Note the difference // Ordinary interface interface discount1{getNum : (price:number) = number}// Function type interface interface discount2{// Note: // ":" The previous one is the signature of the function, which is used to constrain the parameters of the function // ":" The following return value used to constrain the function (price:number):number}let cost:discount2 = function(price:number):number{ return price * .8;}// You can also use type alias type Add = (x: number, y: number) = numberlet add: Add = (a: number, b: number) = a + b
What is the class type interface
- If the interface is used for a class, then the interface will represent the "abstract of behavior"
- constraints on the class, allowing the class to implement the interface. The class can implement multiple interfaces
- The interface can only constrain the public members of the class (instance attributes/methods) and cannot constrain private members, constructors, static attributes/methods
// The interface can be represented as abstract interface of behavior in object-oriented programming Speakable {name: string; // ":" The preceding is the function signature, which is used to constrain the parameters of the function // ":" The return value used to constrain the function speak(words: string): void}interface Speakable2 {age: number;}class Dog implements Speakable, Speakable2 {name!: string;age = 18;speak(words: string) {console.log(words);}}let dog = new Dog();dog.speak('Wog wool');
What is a hybrid type interface
- An object can be used as a function and object at the same time
interface FnType {(getName:string):string;}interface MixedType extends FnType{name:string;age:number;}
interface Counter {(start: number): string;interval: number;reset(): void;}function getCounter(): Counter {let counter = Counterfunction (start: number) { };counter.interval = 123;counter.reset = function () { };return counter;}let c = getCounter();c(10);c.reset();c.interval = 5.0;
inheritance vs polymorphic
- inheritance : Subclasses inherit the parent class. In addition to all the features of the parent class, subclasses also have some more specific features
- polymorphic : Different related classes are produced by inheritance, and different responses can be made to the same method
This is very easy to understand if you have learned Java. I was developing Java before.
For example:
class Animal {speak(word: string): string {return 'Animal: ' + word;}}class Cat extends Animal {speak(word: string): string {return 'Cat:' + word;}}class Dog extends Animal {speak(word: string): string {return 'Dog:' + word;}}let cat = new Cat();console.log(cat.speak('hello'));let dog = new Dog();console.log(dog.speak('hello'));
What is the use of optional chain operator
- Optional chain operator is a type of operator , which first checks whether the attribute exists, and then tries to access the attribute. The symbol is ?.
- If the operand to the left of the operator is calculated as undefined or null, the expression is evaluated as undefined. Otherwise, the target property access, method or function call is triggered normally.
- optional chain operator is in the stage3 stage. You can use the @babel/plugin-proposal-optional-chaining plug-in in advance. TS 3.7 version officially supports use. Previous versions will report an error
a?.b;// equivalent to a == null ? undefined : a.b;// If a is null/undefined, then return undefined, otherwise return the value of a.b.a?.[x];// equivalent to a == null ? undefined : a[x];// If a is null/undefined, then return undefined, otherwise return the value of a[x] a?.b();// equivalent to a == null ? undefined : a[x];// equivalent to a == null ? undefined : a[x];// If a is null/undefined, then return undefined, otherwise return the value of a[x] a?.b();// equivalent to a == null ? undefined : a.b();// If a is null/undefined, then return undefined// If a.b is not a function, a type error exception will be thrown, otherwise the result of a.b() is calculated
What is the type of the extension global variable
interface String {// This is an extension, not an overwrite, so use double(): string;}String.prototype.double = function () {return this + '+' + this;};console.log('hello'.double());// If this is added, an error will be reported// export {}
How to write react + ts version of HOC
interface Greeting {name: string;age: number;}const Hello:React.FCGreeting = (props) = h1Hello {props.name}/h1;// It is recommended to use the second type of const Hello2 = (props:Greeting) = h1Hello {props.name}/h1;
function assignment
JS There is no problem with variables being assigned casually,
but in TS The functions in the middle cannot be assigned casually, and will report errors.
TS Upgrading the content of
requires some brain cells. After all, it is not that easy to learn a language. It is best to understand the basic content thoroughly before learning it.
mainly needs to master joint types, cross types, type alias, type protection, type assertions
abstract classes, polymorphisms, conditional types, etc.
summary:
I studied TS before, and I was working hard on TS documents. It was very boring, it was difficult to get started, and the learning efficiency was very low, and I forgot after learning it.
Later I discovered that we don’t necessarily need to learn so much knowledge, just be able to get started. TS’s documentation is more suitable for reading and use after getting started, and is not suitable for beginners. Basic Type · TypeScript Chinese website · TypeScript - JavaScript superset
Many people who have learned a lot about TS are even doing TS-type gymnastics. They brush TS like LeetCode. As a brick mover, there is really no need to follow the trend. After all, you don’t need to learn so deeply when dealing with daily additions, deletions, modifications and checks.
My philosophy has always been to learn after using it, don’t be anxious, people have limited energy. For example, when I need to understand the source code of Vue3 or design a library, the current TS knowledge reserves are insufficient, so it is not too late to do type gymnastics.
recently re-learned TS, and checked many tutorials that are more easy to understand than official documents, summarized the key points in the study, and formed this article.