Introduction: As Typescript is a superset of JavaScript, it is becoming more and more popular in today’s projects, so let’s learn some of the basics of Typescript.

1. The TypeScript

TypeScript is typed JavaScript that not only supports all of JavaScript’s features, but also adds statically typed annotation extensions on top of JavaScript. Such as:

let a: number = 1;
Copy the code

2.TypeScript data types

TypeScript data types are divided into basic and complex data types.

2.1 Basic data types

string

We can use string to represent any string (including template strings) as follows:

let firstname: string = 'Captain'; // String literal

let familyname: string = String('S'); // Explicit type conversion

let fullname: string = `my name is ${firstname}.${familyname}`// Template string

Copy the code
digital

We can use the number type to represent decimal integers and floating-point numbers, as well as binary, octal, and hexadecimal numbers, as follows:

/** The decimal integer */

let integer: number = 6;

/** The decimal integer */

let integer: number = Number(36);

/** Decimal floating point number */

let decimal: number = 1.33;

/** Binary integer */

let binary: number = 0b0101;

/** octal integer */

let octal: number = 0o725;

/** A hexadecimal integer */

let hex: number = 0xf90b;

/** Large integer */

let big: bigint =  100n;


Copy the code

Note: Number and Bigint are two different types and are incompatible

Boolean value
/ * * really * /

let TypeScriptIsGreat: boolean = true;

 / * * no * /

let TypeScriptIsBad: boolean = false;

Copy the code
Symbol
let s1: symbol = Symbol(a);let s2: symbol = Symbol(The '42');

Copy the code
An array of

First, we can define the array type directly using the form [], as follows:

/** The child elements are arrays of numeric type */

let arrayOfNumber: number[] = [1.2.3];

/** The child element is an array of type string */

let arrayOfString: string[] = ['x'.'y'.'z'];

Copy the code

Similarly, we can define Array types using Array generics, as follows:

/** The child elements are arrays of numeric type */

let arrayOfNumber: Array<number> = [1.2.3];

/** The child element is an array of type string */

let arrayOfString: Array<string> = ['x'.'y'.'z'];

Copy the code

2.2 Complex data types

any

The any type is propagated in the call chain of the object, that is, any property of any type is of type ANY, as shown in the following code:

let anything: any = {};

let z = anything.x.y.z; // if the z type is any, no error will be displayed

z(); // No error will be displayed

Copy the code

Any refers to an arbitrary type, which is an official cheat that selectively circumvents static type detection. We can assign a value of any type to a variable of type any, and a value of type any to a variable of type never, as shown in the following code:

let anything: any = {};

anything.doAnything(); // No error will be displayed

anything = 1; // No error will be displayed

anything = 'x'; // No error will be displayed

let num: number = anything; // No error will be displayed

let str: string = anything; // No error will be displayed

Copy the code

But remember: Any is Hell.

Using any is definitely a bad habit in the long run. If a TypeScript application is full of any, static type detection is of little use, that is, no different from using JavaScript directly. Therefore, we should avoid using any unless there is a good reason.

unknown

Unknown is a type added in TypeScript 3.0 to describe variables of uncertain type. Prior to 3.0, the use of any was the only way to satisfy this dynamic typing scenario.

For example, in multiple if else conditional branching scenarios, it can be used to receive temporary variables that return values of different types under different conditions:

let result: unknown;

if (x) {

  result = x();

} else if(y) { result = y(); }...Copy the code

Unlike any, unknown is more secure on types. We can assign any type of value to unknown, but a value of unknown type can only be assigned to unknown or any, as follows:

let result: unknown;

let num: number = result; / / hint ts (2322).

let anything: any = result; // No error will be displayed

Copy the code

When using Unknown, TypeScript does type detection for it, and all type reduction methods are valid for unknown, such as:

let result: unknown;

if (typeof result === 'number') {

  result.toFixed(); // The hover result prompt type is number

}

Copy the code
Void, undefined, null

Void, which applies only to functions that have no return value. That is, if the function returns no value, it is of type void. In strict mode, declaring a variable of type void has almost no practical use, since we cannot reassign the value of a variable of type void to any variable other than any and unkown.

Undefined is most useful for the interface type, which represents a defaultable, undefined attribute. We can assign a value of undefined or of type undefined to a variable of type void. Conversely, we cannot assign a value of type void to a variable of type undefined.

constuserInfo: { id? : number; } = {};let undeclared: undefined = undefined;

let unusable: void = undefined;

unusable = undeclared; // ok

undeclared = unusable; // ts(2322)

Copy the code

The value of NULL is mainly in interface specification, indicating that an object or property may be null. Especially in the interface of the front and back end interaction, any attributes or objects involved in the query may be null objects, such as:

const userInfo: {

  name: null | string

} = { name: null };

Copy the code
never

Never indicates the type of value that never occurs

First, we define a function that uniformly throws an error, as shown in the following example (after parentheses: + type annotation indicates the type of the value returned by the function) :

function ThrowError(msg: string) :never {

  throw Error(msg);

}

Copy the code

The above function never returns a value, so its return value type is never.

Similarly, if the function code is an infinite loop, the return type of the function is never, as follows:

function InfiniteLoop() :never {

  while (true) {}}Copy the code

Never is a subtype of all types and can be assigned to all types, but conversely, no type (including any) can be assigned to never except never itself.

Under the type-guard condition of constant false, the type of the variable shrinks to never (never is a subtype of all other types, so the type shrinks to never rather than becoming never). As a result, operations related to conditional judgments always report uncorrectable errors (we can think of this as a Dead Code detection mechanism based on static type detection), as shown in the following Code:

const str: string = 'string';

if (typeof str === 'number') {

  str.toLowerCase(); // Property 'toLowerCase' does not exist on type 'never'.ts(2339)

}

Copy the code

Based on the never feature, we can use never as an attribute type of the interface type to forbid writing specific attributes of the interface, such as:

const props: {

  id: number, name? : never } = {id: 1

}

props.name = null; // ts(2322))

props.name = 'str'; // ts(2322)

props.name = 1; // ts(2322)

Copy the code

At this point, no matter what type we assign to props. Name, it will give a type error, which is the same as name read-only.

object

The object type is non-primitive type, that is, non-number, string, Boolean, bigint, symbol, NULL, undefined type. The types used to represent Object.create are shown below.

declare function create(o: object | null) :any;

create({}); // ok

create(() = > null); // ok

create(2); // ts(2345)

create('string'); // ts(2345)

Copy the code

reference

Getting started with TypeScript