The following is a summary of some of my own experiences in the education column Getting Started with TypeScript

Syntactically, TypeScript for default type annotations is identical to JavaScript. So we can think of TypeScript code as adding type annotations to JavaScript code where primitive types are non-object data types that have no methods, It includes string, number, Bigint, Boolean, undefined, and symbol. (NULL is a pseudo-primitive type that is actually an object in JavaScript, And all structured types are derived from the NULL stereotype chain. Primitive type values are the lowest level implementation and the lowest level TypeScript type

string

In JavaScript, we can use string to represent any string in JavaScript (including template strings), as shown in the following example:

let firstname: string = 'Forest'; // string literals let familyName: string = string ('C'); Let fullName: string = 'my name is ${firstName}.${familyName}'; // Template stringCopy the code

All of the JavaScript supported methods for defining strings are available in TypeScript

digital

Similarly, we can use the number type to represent decimal integers and floating-point numbers that JavaScript already supports or will soon support, as well as binary, octal, and hexadecimal numbers, as shown in the following example:

/** Decimal integer */ let integer: number = 6; /** Decimal integer */ let integer2: number = number (42); /** decimal float */ let decimal: number = 3.14; /** let binary: number = 0b1010; /** octal int */ let octal: number = 0o744; /** Hexadecimal integer */ let hex: number = 0xf00D;Copy the code

If we use fewer large integers, we can use the bigint type

let big: bigint =  100n;
Copy the code

::: warning

Although number and Bigint both represent numbers, the two types are incompatible.

: : :

Boolean value

Using Boolean said true or false, the values can be compared (= = = = = | |, & &), can the negative (!)

/** TypeScript true */ let typeScriptIsGreat: Boolean = true; /** TypeScript sucks */ let typeScriptIsBad: Boolean = false;Copy the code

symbol

Since ECMAScript 6, TypeScript supports a new primitive type of Symbol, which allows us to create a unique Symbol through the Symbol constructor. Also, you can use symbol to represent the type shown in the following code

let sym1: symbol = Symbol();
let sym2: symbol = Symbol('42');
Copy the code

TypeScript also includes types such as Number, String, Boolean, and Symbol (case sensitive); Represents a type literal when uppercase

any

Any refers to an arbitrary type and is the godfather of a type. It pays all the price for the purpose, but don’t ask it for pure cotton unless it has to; In TypeScript, you always compile with a type. If you can’t determine what type it is, default is any; This is a last-ditch type and should be avoided whenever possible; Values of type any are just like regular JavaScript. We can do anything with variables that are annotated as type any, including getting properties and methods that don’t actually exist, and TypeScript can’t detect whether the properties exist or are of the correct type. The type checker is completely useless

let anything: any = {}; anything.doAnything(); // no error if anything = 1; // no error if anything = 'x'; Let num: number = anything; // let STR: string = anything; // No error will be displayedCopy the code

The any type is propagated in the call chain of the object, that is, all arbitrary properties of any type are of type ANY

let anything: any = {}; let z = anything.x.y.z; // if z is of type any, there is no error z(); // No error will be displayedCopy the code

unknown

The unknown type is used to describe variables whose type is uncertain. Values of the unknown type can be compared, negated, and refined using JavaScript’s Typeof and Instanceof operators

For example, in multiple if else conditional branching scenarios, it can be used to receive temporary variables with different types of return values under different conditions, as shown in the following code:

let result: unknown; if (x) { result = x(); } else if (y) { result = y(); }...Copy the code

Unlike any, unknown is more secure on types. For example, we can assign a value of any type to unknown, but a value of unknown type can only be assigned to unknown or any, as shown in the following code:

let result: unknown; let num: number = result; // prompt ts(2322) let anything: any = result; // No error will be displayedCopy the code

When unknown is used, TypeScript does type checking for it. However, without Type Narrowing, any operation we perform on Unknown will have the following error:

let result: unknown; result.toFixed(); / / hint ts (2571).Copy the code

All type reduction methods are valid for Unknown, as shown in the following code:

let result: unknown; if (typeof result === 'number') { result.toFixed(); // the hover result 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 and null are the only exceptions where TypeScript values have the same name as type keywords

let undeclared: undefined = undefined; 
let nullable: null = null; 
Copy the code

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.

const userInfo: { id? : number; } = {}; let undeclared: undefined = undefined; let unusable: void = undefined; unusable = undeclared; // ok undeclared = unusable; // ts(2322)Copy the code

In addition, the undefined and null types also serve as a warning that we should be fault-tolerant when we can manipulate these two values. This is to determine whether the type of the value supports the current operation before the operation is performed. Type guarding can influence TypeScript type detection through type reduction and also ensure JavaScript runtime security, as shown in the following code:

const user: { id? : number; name? : null | string } = { id: 1, name: 'Captain' }; if (userInfo.id ! == undefined) { userInfo.id.toFixed(); // The type of id is reduced to number}Copy the code

We can use non-null assertions to rule out cases where the value may be null or undefined, but this is not safe.

userInfo.id! .toFixed(); userInfo.name! .toLowerCase()Copy the code

More secure than non-null assertions and more convenient for type guarding are the single question mark (Optional Chain) and double question mark (null value merge). We can use these to secure our code, as shown in the following code:

userInfo.id? .toFixed(); // Optional Chain const myName = userInfo.name?? `my name is ${info.name}`; // null mergeCopy the code

never

Never indicates the type of value that never occurs

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.

Never is a subtype of all types and can be assigned to all types; On the other hand, no type (including any) can be assigned to the never type except never itself.

let Unreachable: never = 1; // Unreachable = 'string'; // Unreachable = true; Let num: number = Unreachable; // ok let str: string = Unreachable; // ok let bool: boolean = Unreachable; // okCopy the code