TypeScript goes from installation to use

  • The installationtypescript
npm install -g typescript
Copy the code
  • Create a filetypescript.ts
function sayHello(name) {
  return 'hello' + name
}
console.log(sayHello('Bob'))
Copy the code
  • Compiled into js
tsc typescript.ts
Copy the code

The transition from TypeScript to JavaScript is like the one above, which opens the door to TypeScript, but if we want to understand the language we have to look at what it has to offer, right

TypeScript base types

Boolean, Number, String, Array Array, Tuple Tuple Elements need not be of the same type 】, Enum, Any type Any, Void, Null, and Undefined, Never for values that Never exist, unique Symbol

Boolean valueboolean

True /false~ : true/false~ : true/false

let isEat: boolean = false;
Copy the code

digitalnumber

Like JavaScript, all numbers in TypeScript are floating point numbers. These floating point numbers are of type number. In addition to supporting decimal and hexadecimal literals, TypeScript also supports binary and octal literals introduced in ECMAScript 2015.

let num: number = 1;
let hexNum: number = 0xf00d;
let binaryNum: number = 0b1010; // Binary representation in ES6
let octalNum: number = 0o744; // Octal notation in ES6
let notANumber: number = NaN;NaN is the only value in JavaScript that is not equal to itself
let infinityNumber: number = Infinity;// Infinity/ -infinity plus or minus Infinity
Copy the code

stringstring

Covers all functionality in JS, the only difference being declarations

let str: string = "Start";
Copy the code

An array ofarray

There are two ways to define an array

//1. The element type is followed by []
let nums1: number[] = [1.2.3];

// Array generics, Array< element type >
let nums2: Array<number> = [1.2.3];

let nums3: (number | string) [] = [1."2".2];
Copy the code

tuplesTuple

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 of type string and number.

// Declare a tuple type
let x: [string.number];
/ / initialization
x = ['hello'.10]; // OK
// Initialization error
x = [10.'hello']; // Error
Copy the code

When accessing an element with a known index, the correct type is obtained.

console.log(x[0].substr(1)); // h
console.log(x[1].substr(1)); // Error, type 'number' does not have 'substr' method
Copy the code

When accessing an out-of-bounds element, union types are used instead, which is an advanced topic that will be discussed later

x[3] = 'world'; / / OK, strings can be assigned to (string | number) type

console.log(x[5].toString()); // OK, 'string' and 'number' both have toString

x[6] = true; / / Error, Boolean not (string | number) type

// An error occurs when printing added elements
console.log(x[2]); // error [tuple is a known array]
Copy the code

The enumerationEnum

Enumeration types are used to define collections of values. Enumeration types are used to give friendly names to a set of values.

enum Color {Red, Green, Blue};
let c: Color = Color.Blue;
console.log(c);    2 / / output

// Mix enumeration
enum Enum {
  A,
  B,
  C = "i am C",
  D = "i am D",}enum Char {
    // Constant member: the result is computed at compile time
    a,         // No initial value
    b = Char.a,// A reference to a constant member
    c = 1 + 1.// Constant expression
    // computed Member Computes members: Expressions are reserved until the execution phase of the program
    d = Math.random(),// nonconstant expression
    e = '123'.length,
    // The enumerator immediately after the calculated member must have an initial value
    f = 6,}Copy the code

Any typeAny

Any type can be classified as any, and any (any value) is a TypeScript data type for variables that are not typed at programming time. It is used in three cases.

  1. When the value of a variable changes dynamically, such as input from the user, any value type can allow these variables to skip type checking at compile time, as shown in the following example:
let x: any = 1;    // Number type
x = 'I am String';    // A string of characters
x = false;    // Boolean type
Copy the code
  1. Arbitrary values allow optional inclusion or removal of type checking at compile time when overwriting existing code, as shown in the following example:
let x: any = 4;
x.sayHello();    // Yes, the sayHello method may exist at runtime, but it is not checked here
x.toFixed();    / / right
Copy the code
  1. Example code for defining arrays that store various types of data is as follows:
let arrayList: any[] = [1.false.'fine'];
arrayList[1] = 100;
Copy the code

No typeVoid

Used to identify the type of value returned by a method, indicating that the method has no return value.

function sayhello() :void {
    alert("Hello World");
}
Copy the code

Lack of objectnull

Indicates that the object value is missing.

undefinedundefined

Used to initialize a variable to an undefined value.

  1. null

Null in JavaScript means “nothing”. Null is a special type with a single value. Represents an empty object reference. Typeof null returns object.

In JavaScript, undefined is a variable that has no set value.

Typeof a variable with no value returns undefined.

Null and Undefined are subtypes of any other type, including void, and can be assigned to other types, such as numeric types, in which case the assigned type becomes Null or Undefined. With strictNullChecks enabled in TypeScript, null and undefined can only be assigned to void or its own type, as shown in the following example:

/ / enabled - strictNullChecks
let x: number;
x = 1; // Run correctly
x = undefined;    // Error running
x = null;    // Error running
Copy the code

The difference between Null and Undefined is that Null means there is no value and Undefined means there is a value

A value that never existsNever

Never is a subtype of other types, including null and undefined, and represents a value that never occurs. For example, a throwError is raised in a function, or the switch does not catch a value and does not have a default, which causes it to fail to walk to the end and return. When you call this function, you can test never to know that the function is in error, not void. Void indicates that the execution is complete. This means that a variable declared as type never can only be assigned by type never, and in functions it usually behaves as throwing an exception or failing to execute to a termination point (such as an infinite loop).

// A function that returns never must have an unreachable end
function error(message: string) :never {
    throw new Error(message);
}

// The inferred return value type is never
function fail() {
    return error("Something failed");
}

// A function that returns never must have an unreachable end
function infiniteLoop() :never {
    while (true) {}}Copy the code

Unique valuesymbol

Starting with ES6, symbol is a new primitive type that can be used as an attribute of an object, just like number and string

//symbol is constructed using the symbol function, but does not require new
let sym1 = Symbol(a);let sym2 = Symbol("key"); // The optional string key
let sym3 = Symbol("key");
sym2 === sym3;  //false

Copy the code

TypeScript association types

Joint type (Union Types) can be set through the pipe (|) variable Types, assignment can be assigned according to the type of set.

Note: Only the specified type can be assigned. An error is reported if any other type is assigned.

Syntax format:

Type1|Type2|Type3 
Copy the code

Declare an instance:

let name:string|number 
name = 12 
console.log("Code name: + name) // The code is 12
name = "Shop girl" 
console.log("The name is:" + name) // The name is: shopkeeper

// An error is reported if a peculiar type is assigned
name = true // Error
Copy the code

Associative type array:

let arr:number[] |string[]
arr = [1.2.4] // Array of numbers
arr = ["Zhao"."Money"."Sun"."Li"] // Array of strings
Copy the code

TypeScript Interfaces (emphasis)

An interface is a set of abstract method declarations, a collection of method characteristics that should be abstract and implemented by a concrete class that can then be invoked by a third party to make the concrete class execute the concrete method.

  1. Defines the interface
/**
interface 名字 {

}
*/
/ / define
interface Person {
    firstName:string.lastName:string.sayHi: () = >string 
}
/ / use
let customer:Person = {
    firstName:'shop'.lastName: 'small 2'.sayHello: (a) :string= > 'hello'
}
Copy the code
  1. Combine types and interfaces
interface Person {
    firstName:string.lastName:string.hobby: string[] |string.sayHello: () = >string
}
/ / use
let customer:Person = {
    firstName:'shop'.lastName: 'small 2'.hobby: 'Beat wang Erxiao'.//[' run ',' play ']
    sayHello: function () :string {return 'hello'+ this.hobby.toString()}
}
Copy the code
  1. Interfaces and Arrays
interface listName { 
   [index:number] :string 
}

let myArr:listName = ["JorDon".true."Bob"] //Error: true is not string

interface ages { 
   [index:string] :number 
} 
let agelist:ages;
agelist["JorDon"] = 15   / / right
agelist[2] = "15"   // error 2 not string && "15" not number

Copy the code
  1. Interface inheritance

Interface inheritance means that interfaces can extend themselves through other interfaces. Typescript allows interfaces to inherit from multiple interfaces using the extends keyword.

Interface_name_child extends interface_name_father. Interface_name_father extends interface_name_father. : Interface_name_child extends interface_name_father1, Interface_name_father2,... ,interface_name_fatherNCopy the code
  • Single inherited instance
interface Father { 
   name: string 
}
interface Son extends Father {
   age: number
}

let Bob = <Son>{};
Bob.age = 27
Bob.name = 'Bob'
console.log("Name:"+ Bob.name)
console.log("Age:"+ Bob.age)

Copy the code
  • Multiple inheritance instance
interface Father {
    firstName: string,}interface Mather {
    lastName: string,}interface Son extends Father,Mather{
    age: number
}
let Bob:Son = {
    firstName:'Bob'.lastName:'Nasa'.age:18
}
console.log(Iobj)
Copy the code