preface

Recently, when Xiao Ling was maintaining the code written by her former colleague, she often didn’t know what type to input because the old code lacked comments. Thinking that if you had designed your code in Typescript from the start, it would be much more maintainable later on.

Typescript is a programming language based on JavaScript that addresses the shortcomings of JavaScript’s own type system.

Why use TypeScript

JavaScript has no type restrictions at all, and the word for it is “capricious.”

Thus the reliability of the type is lost. When we use a variable, we have to worry about whether it is the type we want. So the language comes across as “unreliable.”

For example, since there are no parameters, a function that used to take two parameters of type number has completely changed its function by entering the string format.

May be careful in the notes, read carefully may not have a problem. But Typescript is a great way to overcome the old saying that “gentleman’s conventions are dangerous and enforce security,” making your code much more reliable.

Installation and Configuration

The installation

Install using NPM or YARN

npm

npm init
npm install -g typescript
Copy the code

yarn

yarn init
yarn add typescript
Copy the code

The module is successfully installed if related JS packages exist.

configuration

Initial Configuration

yarn tsc init
Copy the code

If tsconfig.json is displayed in the root directory, the initial configuration is successful.

The following is an explanation of important configurations:

The strict mode includes:

The rules explain
noImplicitAny Variables or function arguments are not allowed to have an implicit any type
noImplicitThis This context is not allowed to be defined implicitly
strictNullChecks The possibility of null or undefined is not allowed
strictPropertyInitialization Validates the properties defined before and after initialization inside the constructor
strictFunctionTypes Strictly contravariant comparison of function parameters

type

The base type

The basic Typescript types include:

The data type The keyword
Any type any
Numeric types number
String type string
Boolean type boolean
An array type There is no
tuples There is no
The enumeration enum
void void
null null
undefined undefined
never never

The Object type

The Object type in Typescript is not just an Object type. Instead, it refers to all non-primitive types: objects, arrays, and elements.

// Error "sex" is not of type "{name: string; age: number; } ".
const foo: {name:string.age:number} = {name:"Iron".age:18.sex:'male'}
Copy the code

An array type

There are two ways to declare arrays

The first is to use Array generics

The second way is to declare an array type as an element type with square brackets

const arr1:Array<number> = [1.2.3]
const arr2:number[] = [1.2.3]
Copy the code

A tuple type

A tuple type is a special data structure that is an array with an explicit number of elements and each element type.

const tuple:[number.string] = [18.'lwh']
Copy the code

Used to return multiple return values in a single function, such as object.entries provided in React useState() and ES2017 (get an array of keys and values in an Object), whose return argument is a tuple.

Enumerated type

A tuple type is used to represent an array with a known number and type of elements. The types of each element need not be the same.

enum typeDict {
    // 1 = 'video' // Enumerators cannot have numeric names.
    video = 'video',
    mp3 = 'audio',
    link = 'links'
}

const course = {
    title:"Himalayan Course A".content:"What you learn is what you say.".type: typeDict.video
    // video mp3 audio link
}
Copy the code

Function types

We can also use this when we need an optional argument? In the form.

If you need to set default values for parameters, you can refer to ES6 default parameters.

If we are unsure of the number of arguments, we can also refer to the REST operator of ES6.

Any type

Because JavaScript is weakly typed, many of its own methods accept weakly typed arguments. Because Typescript is built on top of JavaScript, it’s inevitable that we use a variable that accepts any type of argument.

Note: Any is primarily used in JavaScript to be compatible with older code.

Implicit judgment of type

In Typescript, if we don’t explicitly mark the type of a variable with a type annotation, Typescript will infer your type based on how you use it.

If we declare a variable without assigning it a value, Typescript can implicitly infer that it is any, and we can then assign it to any value.

Type assertion

There are special cases where Typescript can’t infer the exact type of a variable, and we, as developers, know exactly what type a variable is when the program is executing.

We can see that the find of the above code is likely to find undefined or number. The program logic tells us that the returned RES must be of type number.

There are two ways to implement assertions:

The first is to use AS (the first is recommended).

The second option is to use Angle brackets on variables (this one will conflict with JSX tags).

// is an array of numeric types returned by an explicit interface
const nums = [111.222.111]

const res = nums.find(i= > i > 1000)

// The object may be undefined
// let square:number = res + res

/ / as implementation
const numas = res as number


const numasSum:number = numas * numas
// Angle brackets
const numjian:number = <number>res 

const numJianSum = numjian * numjian
Copy the code

Classes and interfaces

interface

An interface can be understood as a specification or contract. It is an abstract concept that can be used to dictate the structure of our objects. To use an interface, we must follow all the conventions of that interface.

For example, if we need to implement a method that prints course information, we need the required parameters title, content, and PIC. If the parameter implements the interface, our argument must have properties in the interface.

Interface added

There are also special uses for members in interfaces.

// Course interface
interface Course{
    title:string;
    remark:string;
    pic:string; workName? :string; // Optional member
    readonly price:number; // Read-only member
}
Copy the code

We first look at optional members, when a member of our object is optional, and general course assignments are optional. So we can do that by saying the question mark after the workName variable name, right? To represent optional members. This is equivalent to marking workName with type string or undefined.

Then let’s look at read-only members. Normally, the price of our course is not allowed to be set externally, so let’s add a readonly in front of the price variable. Properties can only be set once during initialization and cannot be modified after that.

Finally, when we look at the use of dynamic members, we do not know what specific members will be when we redefine the interface. We can use dynamic members. Our dynamic member is of type string, and an error is reported if it is assigned to another type.

Classes (important concepts in programming)

Class can be said to be the most important concept in object-oriented programming, about the role of class we will briefly describe, mainly describes the abstract characteristics of a class of transactions.

Before ES6, the way to implement classes was function + prototype simulation.

JavaScript has had a dedicated class since ES6.

Typescript goes beyond the classes provided by ES6.

Declare a class:

class Person {
    name: string; // init name
    public readonly age: number;  / / = 15
    protected  gender: boolean; // 
    constructor(name:string,age:number){
        this.name = name
        this.age = age
        this.gender = false
    }
    /** ** say a word *@param MSG information * /
    sayHi(msg:string) :void{
        console.log(msg); }}Copy the code

We declare a class and create a constructor, where we can still type the constructor’s arguments. It’s worth noting that in Typescript properties of our classes must have initial values, which can be assigned at declaration time or in constructors.

Access modifier

Next, let’s look at access modifiers, which we modified a little bit in the class we declared earlier. In fact, both variables and methods can have access modifiers.

A private member can only be used inside a class, and an error will be reported if it is called outside the class. In the following code, we use the private age property to modify the internal age variable when the class is instantiated.

We can use public to decorate members of a class to make them publicly accessible, but Typescript’s default member modifier is public.

There is also a modifier called protected, which we can declare a new member to use. We found that the protected member is still not available in the object instance, which is mainly used by subclasses. We can declare a Student class to inherit from the Person class, and we can see that we can use gender members inside the Student class.

The summary is:

Public, all accessible (default modifier).

Private Private, only allowed inside a class.

Protected, only subclasses and themselves can use it.

Read-only property

In addition to using access modifiers to control our access level, we can also use the readonly keyword to make our members read-only.

Classes and interfaces

Classes implement interfaces through the implements keyword.

These are the two classes that are implemented, cat and dog, and they both have methods of the same name, but they implement them differently. At this point we can understand that they implement the same interface, the protocol.

Some of you are going to say, wouldn’t we just have one parent of the same animal? But animals in the world don’t eat the same way and move the same way, and we need a constraint that they have to have that way and have their own way of doing it.

An abstract class

Abstract classes are similar to interfaces in that they constrain subclasses to have certain members, but an abstract class can contain some concrete implementation whereas an interface can only be an abstraction of one member that contains no concrete implementation.

// Abstract classes can only be inherited
abstract class Animal {
    eat(): void{
        console.log('Edible')}abstract run() :void; // The abstract method must be implemented
}

class Dog extends Animal{

    run(): void {
        throw new Error("Method not implemented.")}}let dog = new Dog();
dog.eat(); // Call abstract class methods directly
Copy the code

Rewriting and overloading

rewrite

/ / rewrite
class Animal {
    public eat() {
        console.log("This is a way to eat.")}}class Dog extends Animal {
    public eat() {
        console.log("This is a way for a puppy to eat.")}}let dog: Dog = new Dog()
dog.eat()
Copy the code

Occurs between a parent class and a child class.

The method name, argument list, and return type (except for a subclass whose method return type is a subclass of its parent) must be the same.

The access modifier must be more restrictive than that of the overridden method (public>protected>private).

overloading

In a class, methods with the same name that have different argument lists (different parameter types, different number of arguments, or even different order of arguments) are considered overloaded.

The generic

Generics, when we define a function interface or class without specifying a specific type, wait until we use it to specify a specific type.

The main purpose of generics is to greatly reuse our code.

/** * Create list *@param length 
 * @param value 
 * @returns * /
function crateList<T> (length:number,value:T) :T[]{
    const arr = Array<T>(length).fill(value)
    return arr
}

const arrString = crateList<string> (3.'xx'); // ['xx','xx','xx']
const arrNumber = crateList<number> (3.15); / /,15,15 [15]
Copy the code

Here we can use an example to illustrate the power of generics. We need to create an Array filled with numbers, so we need the code for the above method because Array by default generates an Array of type Any, and we need to specify its type by

, and when we create an Array of type String we need to copy and then change the type.

Type declaration

Some third-party NPM modules are not necessarily in Typescript, so they don’t necessarily have a strongly typed specification.

For example, let’s download the popular LoDash module, which provides a lot of functions. We call the camelCase function, which converts our string to hump format. It’s a string and it returns a string and it doesn’t have any type indication when we call it.

We can NPM by installing the corresponding type declaration

yarn add @types/lodash
Copy the code

After the installation is complete, the corresponding type error message will be displayed:

Chinese prompt for installation

Typescript is multilingual and defaults to error messages based on the language of your operating system and development tools.

We can use YARN TSC –locale zh-cn to enable the console to support Chinese prompts

yarn tsc --locale zh-CN
Copy the code

For compiler prompts we can set typeScript locale = to zh-cn using file = preference =

Last word

And with the last of those points, we’re coming to the end of today’s sharing. On paper come zhongjue shallow, I believe you will have more profound insights in practical use. In the future use of the findings will be updated in this article, welcome everyone to collect and pay attention to.

The following is the project address: TS Project address