First published at: github.com/USTB-musion…

Writing in the front

Ts is a superset of JS with a type system, which has been very popular in recent years. It can be said that TS is js in the true sense. Although the official DOCUMENTATION of TS is very comprehensive, it will take a long time for students who have not been exposed to TS to read through it. This article is intended for students who are trying to get started with TS.

This paper will summarize from the following parts:

  1. The advantage of the TypeScript
  2. The difference between strong and weak types
  3. The difference between dynamic and static typing
  4. The base type
  5. The interface type
  6. function
  7. class
  8. The generic

The advantage of the TypeScript

1. Help refactor your code better

A good code habit is to always make small refactorings of your code to make it more maintainable. But for a lot of code running online, code test coverage is often not very high, sometimes even a variable name change, will affect the whole. Projects written in TS have no such concerns. The STATIC checking feature of TS helps find the parts of the code that have errors.

2. IDE tips like vscode are smarter

Js is a dynamically weakly typed interpretation language. The type of a variable can be changed after it is declared, and the type must be determined at run time. Ts displays an error at compile time, not run time. So using features like static type checking that TS brings with it will make the IDE’s hints even better.

3. Type declarations are great documentation in and of themselves

When you’re working on a project with historical baggage, you’re going to have to worry about the lack of documentation and code comments. For TS, it’s possible to make the code as documentation by declaring what fields mean and what fields are required and optional. As a simple example, when encapsulating a button component:

export interface ButtonProps { style? : React.CSSProperties className? : string label? : React.ReactNode type? : 'primary' | 'default' | 'search' size? : 'sm' | 'md' | 'lg' | 'mini' disabled? : boolean title? : string onClick? : ((e: React.MouseEvent<HTMLButtonElement>) => void) }Copy the code

As you can see from these declarations, when using the Button file, style is an optional value that represents a style field that you can customize. Type is also an optional value that indicates the color type of the button, which can be ‘primary’,’default’, or ‘mini’. Disabled is also an optional value. The value passed in must be of Boolean type. So you can see that type declarations themselves are pretty good documentation.

The difference between strong and weak types

Strongly typed languages: Strongly typed languages do not allow changing the data type of a variable unless casting is performed.

For example, if a string variable STR is defined, STR cannot be treated as a Boolean, integer, etc., unless cast is performed. C, C ++, Java, etc are strongly typed languages.

Weakly typed languages: Defines that, in contrast to strongly typed languages, a variable can be assigned values of different data types.

var a = '111';
var b = 222;
a = b;
console.log(a) // 222
Copy the code

As shown in the js code above, a is a string variable and b is an integer variable, but it is possible to assign b to A, which prints 222.

The rigor of strong typing effectively prevents many errors.

The difference between dynamic and static typing

Dynamically typed languages: Type checking is done at execution time.

For example, JS/Python is a dynamically typed language, which is very lax about type checking, and bugs can hide for a long time before being discovered.

Statically typed languages: Type checking is done at compile time

For example, c++/Java are statically typed languages that are very strict about type checking and bugs are found at compile time. Code is documentation.

The base type

ES6 types can be divided into Boolean, Number, String, Array, Function, Object, Symbol, undefined, null. TypeScript’s data types add void, any, never, tuples, enumerations, and advanced types to ES6.

The basic grammar

: type

TypeScript’s basic type syntax, which uses a colon after a variable for type identification, also reveals that TypeScript type declarations are actually optional.

boolean

Boolean is the most basic data type. In TS, Boolean is used to define Boolean values

let isDone: boolean = false;
Copy the code

number

In TS, number is used to define numeric types

let num: number = 123

Copy the code

string

In TS, string is used to define the string type

let name: string = 'jarod'
Copy the code

array

In TS, there are two ways to define an array. One way is to define an array of elements by following the element type with [] :

let arr1: number[] = [1, 2, 3]
Copy the code

Another option is to use Array generics, Array< element type > :

let arr2: Array<number> = [1, 2, 3]

Copy the code

tuples

What if YOU want to represent different elements in an array? This is where the tuple type comes in. The tuple type allows you to represent an array with a known number and type of elements that need not be of the same type. For example, you can define a pair of tuples with values of number and string.

let hello: [number, string] = [0, 'hello']
Copy the code

The enumeration

Enum types complement the JavaScript standard data types. As in other languages such as C#, enumeration types can be used to give friendly names to a set of values.

enum Month {
    Jan,
    Feb,
    Mar
}
let month = [Month.Jan, Month.Feb, Month.Mar]
Copy the code

never

If a function never returns a value, we can declare it to be void:

function example(): never {
    throw new Error('never');
}
Copy the code

any

Any is a special type of ts. Once declared as any, type checking for ts is turned off.

let x: any = 0;
x = [];
x = false; 
x = '';
Copy the code

A variable of type any can be assigned a value of any type. Using any is friendly for projects that migrate JS. But in real development, use any as little as possible.

void

In TS, void means that the function has no return value.

function example(): void {
    console.log('this is void type');
}
Copy the code

Undefined and null

In TypeScript, undefined and null have their own types called undefined and NULL, respectively. Like void, their own types are not very useful:

let u: undefined = undefined;
let n: null = null;
Copy the code

readonly

Some object properties can only change their value when the object is created. You can use readonly before the property name to specify read-only properties.

interface Props {
    readonly name: string;
}
interface State {
    readonly color: string;
}
export class Child extends React.Component<Props,State> {
  childMethod() {
    this.props.name = 'jarod'; // ERROR: (props are immutable)
    this.state.color = 'red'; // ERROR: (one should use this.setState)  
  }
}
Copy the code

The interface type

In TypeScript, we use Interfaces to define the types of objects.

Object interface

When assigning, the shape of the variable must match the shape of the interface.

interface Name { first: string; second: string; } var personName:Name = {first: ' '} // Property 'second' is missing in type '{first: string; }' but required in type 'Name'Copy the code

Ts checks each field, and if the field declared in the docking port is not defined (optional), you can see that the variable defined has fewer attributes than the interface will throw an error.

The function interface

Interfaces can describe the various shapes that objects in JavaScript can have. In addition to describing ordinary objects with attributes, interfaces can also describe function types

interface Lib { (): void; version: string; doSomething(): void; } function getLib() {let lib = (() => {}) as lib lib.version = '1.0.0' lib.dosomething = () => {} return lib; }Copy the code

function

Function declaration

function sum(x: number, y: number) {
    return x + y
}
Copy the code

Functional expression

let sum =  (x: number, y: number): number => x + y
Copy the code

Optional parameters

For parameters, we can declare them optional by adding “?” after the parameter.

function buildName(firstName: string, lastName? : string) { // ... }Copy the code

Function overloading

Overloading allows a function to take different numbers or types of arguments and behave differently.

function reverse(x: number): number; function reverse(x: string): string; function reverse(x: number | string): number | string { if (typeof x === 'number') { return Number(x.toString().split('').reverse().join('')); } else if (typeof x === 'string') { return x.split('').reverse().join(''); }}Copy the code

class

An abstract class

Abstract classes can only be used in instances, not directly instantiated.

abstract class Animal { eat() { console.log('eat') } abstract sleep(): Class Dog extends Animal {constructor() {super()} sleep() {console.log('Dog sleep')}Copy the code

Public, private and protected

TypeScript uses three types of Access Modifiers, public, private, and protected.

public

Properties or methods decorated by public are public and can be accessed anywhere. By default, all properties and methods are public

class Animal {
    public name;
    public constructor(name) {
        this.name = name;
    }
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
console.log(a.name); // Tom
Copy the code

private

A property or method modified by private is private and cannot be accessed outside the class in which it is declared

class Animal { private name; public constructor(name) { this.name = name; } } let a = new Animal('Jack'); console.log(a.name); // Jack a.name = 'Tom'; / / index. Ts (9, 13) : error TS2341: Property 'name' is private and only accessible within class 'Animal'. // index.ts(10,1): error TS2341: Property 'name' is private and only accessible within class 'Animal'.Copy the code

protected

Protected attributes or methods are protected, just like private, except that they are accessible in subclasses

class Animal { protected name; public constructor(name) { this.name = name; } } class Cat extends Animal { constructor(name) { super(name); console.log(this.name); }}Copy the code

The generic

Definition: Data types that are not defined in advance. The specific type must be determined at the time of use

Example: Declare a print function that prints the string passed in:

function log(value: string): string {
    console.log(value)
    return value
}
Copy the code

But at this point, add a requirement to implement the ability to print an array of strings as well:

function log(value: string): string
function log(value: string[]): string[]
function log(value: any): {
    console.log(value)
    return value
}
Copy the code

This can be done with the previous function overloading, as shown above.

If at this point, there is a requirement to be able to print any type of argument. Generics come in handy:

function log<T>(value: T): T {
    console.log(value);
    return value;
}
Copy the code

In software engineering, it is important not only to create consistent, well-defined apis, but also to consider reusability. The ability of components to support not only current data types but also future data types gives you a lot of flexibility when building large systems.

subsequent

The next step in Typescript practice is coming soon

You can pay attention to my public account “Muchen classmates”, goose factory code farmers, usually record some trivial bits, technology, life, perception, grow together.