This is the 19th day of my participation in the Genwen Challenge
preface
I didn’t have time to summarize the TS study some time ago. Today, when I have time, I will sort out some core knowledge in my learning process into a paper for easy reference in the future
This article features: small, a few minutes can be read quickly
Gain: By reading this article, you will be able to quickly get started with JS and understand the core basics of TS
Attached: The structure preview of this paper is as follows
Introduction to the
TypeScript is a superset of JavaScript designed for large applications.
It has two characteristics:
One is strong type;
The second is object-oriented programming based on class
The data type
There are many types of data in TS, as follows:
Number
type
let a: number = 5
Copy the code
As above, declare an A of type Number and assign the Number 5; You can see the TS declaration variable data type, the format of the variable name followed by: xx type
String
type
let str: string = 'hello ts'
Copy the code
Boolean
type
let isDone: boolean = true
Copy the code
Null
andUndefined
type
let n1: null = null
let u1: undefined = undefined
// -------------------------------
let n2: null = undefined
let u2: undefined = null
Copy the code
A variable defined as null or undefined. Assignment can be either null or undefined
Void
type
function fn() :void{
console.log('This is a fn,but return is void')}Copy the code
Void is used to return null
Any
type
let any1: any = 'xxx'
Copy the code
Variables of type Any can be assigned to values of Any type
let arr: number[] = [1.2.3];
/ / or
let arr: Array<number> = [1.2.3];
Copy the code
Enum
type
enum Direction {
NORTH,
SOUTH,
EAST,
WEST,
}
let dir: Direction = Direction.NORTH;
Copy the code
Note that the above only lists some commonly used data types. The rest can be refer to the official website
Type declaration
TS provides some basic types, and classes can also be used as types. But sometimes we need something more flexible, which means we need to customize some types or type declarations
Declaring a type requires the keyword type for example
type User = { name: string; age? : number; }Copy the code
The above code defines a User type that must have a name attribute of type string and optionally an age attribute of type number
let user: User;
user = {
name: 'Alice'
}
Copy the code
In the above code, declaring a user variable requires that we define the user type and assign it a value corresponding to the defined type
Not just for variables, of course. Custom types, just like normal types, can be used anywhere a type can be used, with no restrictions, such as function parameters and so on
function show(obj: User) {
console.log(obj.name)
}
show(user);
Copy the code
You can see how easy it is to create a new type using the type keyword
Type assertion and type guard
Let’s start with an example
type User = {
name: string;
age: number;
}
function showUser(user: User) {
console.log(user.name);
console.log(user.age);
}
showUser({ name: 'Alice'.age: 12 })
Copy the code
As shown above, the showUser function executes arguments that are type-compliant. However, an error is reported if the parameters do not meet the requirements
let errorType = ' ';
showUser(errorType); / / error
Copy the code
Normally written code would not cause this problem, but the data could come from somewhere else at run time (such as a database, third-party libraries, user input, and so on). We know that languages do not have types at runtime, so how do we ensure and verify that data from elsewhere meets our requirements at runtime? That’s what type assertions do
The so-called assertion is to conclude, certain, absolute meaning; So simply put, a type assertion is a guarantee that the data type must be the required type
Type assertions also require the help of a type-guard function, which is used to determine whether unknown data is of the desired type
function isUser(arg: any) :arg is User {
if(! arg) {return false;
}
else {
if (typeof arg.name == 'string' && typeof arg.age == 'number') {
return true;
} else {
return false; }}}Copy the code
As you can see, a type-guard function is not much different from a normal function, except that its return value is of a special type: x is y, indicating whether x is of type Y
if (isUser(errorType)) {
showUser(errorType);
}
Copy the code
No error is reported after such a type assertion
Class and modifier
class
As we know, the purpose of class is to put related things together for easy management
A class contains two things (also called members) :
- attribute
- methods
The members of a class are all the properties and methods in the class
TS allows you to easily define a class using the class keyword
class Person{
name:string; Age:number;
show(){
console.log(I call `The ${this.name}This year,The ${this.age}The `); }}Copy the code
The new keyword makes it easy to produce instances of a class, a process called instantiation
let p1 = new Person('Alice'.12)
Copy the code
As above, P1 is an instance of the Person class
Another thing to note is that when an instance comes out of new, it actually calls a method in the class to initialize it, and that method is called a constructor; The constructor method is typically written explicitly in the class, and if no defined constructor is shown, the system’s implicit constructor is called
constructor(name:string,age:number){
this.name = name;
this.age = age;
}
Copy the code
A member modifier in a class
Access modifier
The purpose of access modifiers is to prevent others from messing with things in a class
public
Public, anyone can use it (default public)
private
Private, used only by the class itself
protected
Protected, only classes and subclasses can be used
Advice on using access modifiers: Use private as much as possible. Generally, all attributes are private, and private attributes can be accessed through accessors
class Person{
private _num:number = 12;
public get num() {return this._num;
}
public set num(val:number) {this._num = val; }}let p1 = new Person();
console.log(p1.num)
p1.num = 5;
console.log(p1.num)
Copy the code
TSC: ts generates ES4 code by default, and we need to specify the version of ts compiled by –target
tsc --target ES5 1.js
Copy the code
Of course, you can also configure accessors in tsconfig.json files for the benefit of security and convenience
Read-only modifier
Readonly Reads but does not write
class Person{
readonly name = 'Alice';
}
let p = new Person();
console.log(p.name);
Copy the code
Note that even readonly things can be written before initialization, i.e. initialized or changed within constructor
class Person{
readonly name:string;
constructor(name:string){
this.name = name; }}Copy the code
So, we know that the readonly property has only two places to write:
- Assign the initial value at the same time as the declaration
- Assign or modify the initial value in the constructor
Static modifier
Static members are called static members. Static members are called by the class name instead of being instantiated
class Person{
static a = 98;
}
console.log(person.a)
Copy the code
Static members are usually used for something common to the entire class
Pay attention to the point
These three modifiers: access, read-only, and static modifiers can be combined to modify the same member but need to be noted
- Modifiers are optional. If no modifiers are written, there is one by default
public
- There can be only one modifier of the same kind
- The three modifiers are in order: access, static, and read-only
Public /static/protected public/static/protected
Class inheritance
We know that js has inheritance. Js used functions to simulate classes until ES6 introduced the use of class and extends keywords. So why inheritance? In fact, the benefit of inheritance is that you can reuse your code better and maintain it better later
Inheritance in TS class inheritance in ES6 is very familiar. Subclasses can extend a class using the extends keyword for example:
class Person{
name:string;
age:number;
constructor(name,age){
this.name = name;
this.age = age; }}class student extends Person{
score:number;
constructor(name,age,score){
super(a);this.score = score; }}Copy the code
As you can see, as in ES6, the subclass constructor must be added with super() to perform the parent class’s constructor function
So it’s often said that an instance of a subclass is also an instance of a superclass
Inherited format:
class A {}
class B extends A {
constructor() {
super();
}
}
Copy the code
As above, if B inherits A, B is called A superclass, and A is called A subclass. Instances of subclasses are public and protected properties and methods that can inherit from their superclass
In addition to inheritance, there is another feature of object orientation: polymorphism is actually quite common in polymorphic JS and TS, which can be interpreted as multiple states, such as which function to execute at runtime
An abstract class
Abstract means non-concrete, so an abstract class is a non-concrete class. So abstract classes have no function on their own, and are usually used as superclasses
Define an abstract class using the abstract class keyword
abstract class A{
abstract fn():number;
}
Copy the code
An abstract class specifies that all non-abstract subclasses that inherit from it must implement specified functions and operations, or an error will be reported
class B extends A{
constructor(){
super(a); } fn():number{
return 1}}Copy the code
Note that abstract classes are only base classes and cannot be new
let b = new B();/ / can
let a = new A();/ / an error
Copy the code
interface
An interface is a specification, similar to an abstract class
The interface is defined using the interface keyword in the following format:
Interface XXX {attribute: type; . (Function argument) : Return value type... }Copy the code
Interfaces are generally used to regulate three things:
- function
- class
- The constructor
The function interface
The interface function specifies the parameters and return values of a function
interfaceXXX {(parameter,...) : Return value type}Copy the code
For example,
interface SearchFn {
(key: string, page? :number) :number[]}const search: SearchFn = function (key: string, page: number) {
return [1.2.3]}Copy the code
When a function type is interface, it requires:
- The parameter name may be different, but the parameter value type must be the same as the interface definition, and the parameter can be few but not many.
- The return value must be consistent with the interface definition.
The class interface
We know that inheritance has the advantage of reusing code and having a clear hierarchy. But JavaScript inheritance is single inheritance, and a class can only have one parent class. Interfaces are more flexible in TypeScript because they can be implemented in many ways. For example:
interface serialization {
toJSON(): object;
formJSON(json: object) :void;
}
class Box implements serialization {
width: number;
height: number;
constructor(width:number,height:number){
this.width = width;
this.height = height;
}
toJSON(): object {
return { width: this.width, height: this.height }
}
formJSON(json: object) :void {
if (isSize(json)) {
this.width = json.width;
this.height = json.height; }}}function isSize(json: any) :json is { width: number.height: number } {
if (typeofjson ! ='object') {
console.log('Must be of type Object');
} else {
if (typeofjson.width ! ='number' || typeofjson.height ! ='number') {
console.log('width and height must be type number!! ')}}return true;
}
let box = new Box(50.50)
Copy the code
As mentioned above, you can make a class implement an interface through the implements keyword, requiring that the methods defined by the temporal interface be implemented or else an error will occur
Constructor interface
The interface constructor is special in that it is implemented as an assignment and must be distinguished from ordinary interfaces, which still use implements. Also use new in the interface to refer to the constructor
interface BoxConstructorInterface{
new (a:string)
}
interface BoxInterface{
show(a:number):void;
}
const Box:BoxConstructorInterface = class implements BoxInterface {
private a:string;
constructor(a:string){
this.a = a;
}
show(a:number){
console.log(this.a)
}
}
Copy the code
Also, like a class, an interface can inherit from another interface. For example:
interface A { }
interface B extends A { }
class C implements B { }
Copy the code
So, we know that the interface itself is just a specification that defines some required properties or methods. The interface can be used to regulate function, class, or constructor, but the rules are a little different
The generic
Generics can be understood as broad types and are commonly used for classes and functions
A generic class
Generics can be used with classes and constructors, for example:
class Person<T>{
private _value: T;
constructor(val: T) {
this._value = val;
}
}
let p = new Person<number>(12)
Copy the code
As above,
means passing a T type, passing the specific type only on new. T is variable modifiable, but it’s very common when you talk about TypeScript types before you write T and you talk about arrays, which is essentially a generic class
let a = new Array<number>();
Copy the code
Generic function
Generics can be used with ordinary functions, for example:
function fn<T> (arg: T) :T {
return arg;
}
fn<number> (12);
Copy the code
The idea is to pass in a type as a special argument, whether used for a class or a function
It is important to note that generics can also “inherit”, but in terms of limiting scope for example
class Person<T extends Date>{
private _value: T;
constructor(val: T) {
this._value = val; }}let p1 = new Person(new Date())
class MyDate extends Date{}
let p2 = new Person(new MyDate())
Copy the code
The above is my summary of TS, which is the most basic and core grammar of TS! It is suggested that after learning more practice, in order to have a deeper grasp of TS!