The main architecture of the company is already react and typescript, so we’ve reworked typescript

I found that the right way to write it and the wrong way to write it. It seems to learn faster. More powerful ~

Most of us can write correctly, but it is more important for us to remember why we got it wrong

At least it worked for me. All right, let’s cut the crap. Start right away ~

Primitive data type

There are two types of JavaScript: primitive data types and object types.

Primitive data types include: Boolean, numeric, string, NULL, undefined, and the new type Symbol in ES6

This section focuses on the use of the first five primitive data types in TypeScript.

Booleans are the most basic data types. In TypeScript, Boolean is used to define Boolean types:

All of the following are compiled, and the instructions are given. In one sentence, the type is assigned to the type

The correct way to write it

➖➖➖➖➖➖➖➖➖ Boolean ➖➖➖➖➖➖➖➖➖ // Boolean valuelet isDone: boolean = false; // In fact 'new Boolean()' returns a 'Boolean' objectletcreatedByNewBoolean: Boolean = new Boolean(1); //(calling 'Boolean' directly can also return a 'Boolean' type)letcreatedByBoolean: boolean = Boolean(1); ➖➖➖➖➖➖➖➖➖ value ➖➖➖➖➖➖➖➖➖ // Valuelet decLiteral: number = 6;
lethexLiteral: number = 0xf00d; // Binary representation in ES6letbinaryLiteral: number = 0b1010; // Octal notation in ES6let octalLiteral: number = 0o744;
let notANumber: number = NaN;
letinfinityNumber: number = Infinity; ➖➖➖➖➖➖➖➖➖ The value is ➖➖➖➖➖➖➖➖➖let myName: string = 'Tom'; ➖➖➖➖➖➖➖➖➖ void ➖➖➖➖➖➖➖➖➖ // Void for functions with no return valuefunction alertName(): void {
    alert('My name is Tom'); } // Void can only be assigned to undefined and nullletunusable: void = undefined; ➖➖➖➖➖➖➖➖➖Null and Undefined➖➖➖➖➖➖➖➖➖ // Variables of the Undefined type can be assigned only as Undefined, and variables of the Null type can be assigned only as Nulllet u: undefined = undefined;
let n: null = null;
Copy the code

Wrong way to write it

Note: the correct ones are easy to remember, most people can write correctly, the key is to remember the wrong ones!!

➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ Boolean ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ / / note that the use of the constructor ` Boolean ` create object is not a Boolean valueletcreatedByNewBoolean: boolean = new Boolean(1); ❌ ➖➖➖➖➖➖➖➖➖ Value ➖➖➖➖➖➖➖➖➖let decLiteral: number = "6"; ❌ ➖➖➖➖➖➖➖➖➖ The value is ➖➖➖➖➖➖➖➖➖letmyName: string = 999; ❌ ➖➖➖➖➖➖➖➖➖ void ➖➖➖➖➖➖➖➖➖ // Void for functions with no return valuefunctionAlertName () : void {❌return666; } // Void can only be assigned to undefined and nulllet unusable: void = 'I love you'; ❌ ➖➖➖➖➖➖➖➖➖Null and Undefined➖➖➖➖➖➖➖➖➖ // Variables of the Undefined type can be assigned only as Undefined, and variables of the Null type can be assigned only as Nullletu: undefined = 888; ❌letn: null = 999; ❌Copy the code

Any value

The correct way to write it

As the name implies, it can be assigned to any value
let anyThing: any = 'hello';
let anyThing: any = 888;
let anyThing: any = true;
let anyThing: any = null;
let anyThing: any = undefined;

// If the type of a variable is not specified when it is declared, it can be identified as any value type:
let any;
any =true;
Copy the code

Wrong way to write it

There is no wrong way to write ~

Type inference

The correct way to write it

// If there is no explicit Type specified, TypeScript will infer a Type according to the rules of Type Inference.
let myFavoriteNumber = 'seven'; Is equivalent tolet myFavoriteNumber :string= 'seven';
Copy the code

Wrong way to write it

// The first sentence is inferred to be of type String
let myFavoriteNumber = 'seven';
myFavoriteNumber = 7; ❌Copy the code

The joint type

The correct way to write it

// Union Types indicate that the value can be one of many Types.
// When you allow multiple types to be assigned to a variable, use the union type, pipe character for concatenation
let myFavoriteNumber: string | number;
myFavoriteNumber = 'seven';
myFavoriteNumber = 7;

// Can also be used for method arguments, both have toString methods, accessing the common attributes of string and number is no problem
function getString(something: string | number) :string {
    return something.toString();
}
Copy the code

Wrong way to write it

// The number type has no length attribute. So compilation error, because we can only access properties or methods that are common to all types of this union type:
function getLength(something: string | number) :number {❌
    return something.length;
}
Copy the code

The type of the object — interface

The correct way to write it

// When assigning, the shape of the variable must be the same as the shape of the interface (no more, no less, and the type must be the same)
interface Person {
    name: string;
    age: number;
}

let tom: Person = {
    name: 'Tom'.age: 25
};


IUserInfo{
  age : any;// Define an age for any variable.
  userName :string;// Define a username.
}
function getUserInfo(user : IUserInfo) :string{
    return user.age+"= = = = = ="+user.userName; } ➖➖➖➖➖➖➖➖➖ Optional attribute ➖➖➖➖➖➖➖➖➖ interface Person {name: string; age? : number;// indicates that this attribute is optional
}

let tom: Person = {
    name: 'Tom'}; ➖➖➖➖➖➖➖➖➖ Arbitrary attribute ➖➖➖➖➖➖➖➖➖If you want an interface to allow arbitrary attributes, you can do this: Once any attribute is defined, the type of the defined attribute and the optional attribute must be a subset of its type
interface Person {
    name: string; age? : number; [propName: string]: any; }let tom: Person = {
    name: 'Tom'.gender: 'male' // Other attributes can be added}; ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ read-only property ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ interface Person {readonly id: number;// name: string; age? : number; [propName: string]: any; }let tom: Person = {
    id: 89757./ / read-only
    name: 'Tom'.gender: 'male'
};
Copy the code

Wrong way to write it

// Once any attribute is defined, the type of both the determined attribute and the optional attribute must be a subset of its type
interface Person {
    name: string; age? : number; [propName: string]: string; }let tom: Person = {
    name: 'Tom'.age: 25.gender: 'male'❌}; In this example, the value of any attribute can be string, but the value of the optional attribute age is number. Number is not a child of string, so the error is reported. ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ read-only property ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ interface Person {readonly id: number; name: string; age? : number; [propName: string]: any; }let tom: Person = {
    name: 'Tom'.gender: 'male'
};

tom.id = 89757; // cannot be assigned twice ❌
Copy the code

Array type

The right thing to do

let fibonacci: number[] = [1.1.2.3.5];
let fibonacci: Array<number> = [1.1.2.3.5]; ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ expressed in interface array ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ interface NumberArray {/ index: number: the number; }let fibonacci: NumberArray = [1.1.2.3.5]; ➖➖➖➖➖➖➖➖➖ Any in the array ➖➖➖➖➖➖➖➖➖let list: any[] = ['Xcat Liu'.25, { website: 'http://xcatliu.com'}]; ➖➖➖➖➖➖➖➖➖ class array ➖➖➖➖➖➖➖➖➖function sum() {
    let args: IArguments = arguments;
}

Copy the code

Wrong way

// No other types are allowed in the array item:
let fibonacci: number[] = [1.'1'.2.3.5]; ❌// The push method is only allowed to pass a number argument, but it passes a string argument, so it fails.
let fibonacci: number[] = [1.1.2.3.5];
fibonacci.push('8'); ❌// Array-like Object classes are not Array types, such as arguments
function sum() {❌
    let args: number[] = arguments;
}
Copy the code

Type of function

The right thing to do

// Both inputs and outputs need to be taken into account
function sum(x: number, y: number) :number {
    returnx + y; } ➖➖➖➖➖➖➖➖➖ function expression ➖➖➖➖➖➖➖➖➖let mySum = function (x: number, y: number) :number {
    return x + y;
};
// Don't confuse => in TypeScript with => in ES6
let mySum: (x: number, y: number) = > number = function (x: number, y: number) :number {
    returnx + y; }; ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ the shape of the interface definition function ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ interface SearchFunc {(source: string.subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function(source, subString) {
    returnsource.search(subString) ! = =- 1; } ➖➖➖➖➖➖➖➖➖ Optional parameter ➖➖➖➖➖➖➖➖➖function buildName(firstName: string, lastName? : string) {
    if (lastName) {
        return firstName + ' ' + lastName;
    } else {
        returnfirstName; }}let tomcat = buildName('Tom'.'Cat');
let tom = buildName('Tom'); ➖➖➖➖➖➖➖➖➖ Default value ➖➖➖➖➖➖➖➖➖function buildName(firstName: string, lastName: string = 'Cat') {
    return firstName + ' '+ lastName; } ➖➖➖➖➖➖➖➖➖ Remaining parameters ➖➖➖➖➖➖➖➖➖// The rest argument can only be the last argument, in the case of the rest argument, an array
function push(array: any[], ... items: any[]) {
    items.forEach(function(item) {
        array.push(item);
    });
}

let a = [];
push(a, 1.2.3);


Copy the code

Wrong way

It is not allowed to enter extra (or less than required) parameters:
function sum(x: number, y: number) :number {
    return x + y;
}
sum(1.2.3); ❌ the sum (1); ❌It is not allowed to enter extra (or less than required) parameters:
function sum(x: number, y: number) :number {
    return x + y;
}
sum(1.2.3);

// Optional parameters are not allowed after the mandatory parameters:
function buildName(firstName? : string, lastName: string) {❌
    if (firstName) {
        return firstName + ' ' + lastName;
    } else {
        returnlastName; }}let tomcat = buildName('Tom'.'Cat');
let tom = buildName(undefined.'Tom');
Copy the code

assertions

The right thing to do

You can use type assertions to declare something as a string
function getLength(something: string | number) :number {
    if((<string>something).length) { return (<string>something).length; } else { return something.toString().length; }}Copy the code

Wrong way

// Only properties or methods that are common to all types of this union type can be accessed
function getLength(something: string | number) :number {❌return something.length;
}
Copy the code

Type the alias

The right thing to do

// Use type to create a type alias. Type aliases are often used to combine types
type Name = string;
type NameResolver = (a)= > string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver) :Name {
    if (typeof n === 'string') {
        return n;
    } else {
        returnn(); }}Copy the code

The enumeration

The right thing to do

The enumeration (Enum) type is used when the value is limited to a certain range, for example, there are only seven days in a week
// Enumeration is the reverse mapping of enumeration values to enumeration names

enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"]); / / 0
console.log(Days[0]); // 'Sun'

enum Days {Sun = 7, Mon = 1, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"]); / / 7

Copy the code

class

The right thing to do

➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ class ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ class Animal {constructor (name) {enclosing name = name; }sayHi() {
        return `My name is ${this.name}`; }}let a = new Animal('Jack'); console.log(a.sayHi()); // My name is Jack ➖➖➖➖➖➖➖➖➖ ➖➖➖➖➖➖➖➖➖ class Cat extends Animal {constructor(name) {super(name); // Call the parent class's constructor(name) console.log(this.name); }sayHi() {
        return 'Meow, '+ super.sayHi(); SayHi ()}}let c = new Cat('Tom'); // Tom console.log(c.sayHi()); // Meow, My name is Tom ➖➖➖➖➖➖➖➖➖ memory ➖➖➖➖➖➖➖➖➖ class Animal {constructor(name) {this.name = name; } getname() {
        return 'Jack';
    }
    set name(value) {
        console.log('setter: '+ value); this.name = value; }}let a = new Animal('Kitty'); // setter: Kitty
a.name = 'Tom'; // setter: Tom console.log(a.name); / / Jack ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ static methods ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ class Animal {static isAnimal (a) {returna instanceof Animal; }}let a = new Animal('Jack');
Animal.isAnimal(a); // true// call a.isanimal (a) only by class name; // TypeError: a.isAnimal is not afunction❌ ➖➖➖➖➖➖➖➖➖ abstract class ➖➖➖➖➖➖➖➖➖ abstract class Animal {makeSound():void move():void {console.log()'roaming the earch... '// Subclasses must implement abstract methods of abstract classesCopy the code

Public, private and protected

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

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

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

The generic

Generics address the reusability of class interface methods and support for non-specific data types

The right thing to do

// Only string data is returned
function getData(value:string) :string{
  return value;
}

// Both string and number are returned (code redundancy)
function getData1(value:string) :string{
  return value;
}
function getData2(value:number) :number{
  returnvalue; } >>>>>>>>>> Use generics to solve this problem// T stands for generics. What type is determined when this method is called
// Return the type of the parameter
function getData<T> (value:T) :T{
  return value;
}
getData<number>(123);
getData<string>('1214231');

// Define the interface
interface ConfigFn{
    <T>(value:T):T;
}
var getData:ConfigFn=function<T> (value:T) :T{
  return value;
}
getData<string>('Joe');
getData<string>(1243);  / / error
Copy the code

If you think it’ll help you. Might as well on this simple article like attention to go a wave, everyone has their own learning methods, masters can leave footprints in the comments area. We exchange and learn from each other