Follow the documentation to learn TS

The base type

introduce

To make our programs more valuable, we need to be able to handle the simplest units of data: numbers, strings, structures, booleans, etc. TypeScript supports almost the same data types as JavaScript, and it also provides useful enumerated types for us to use.

Boolean value

The most basic data types are simple true/false values, called Boolean in JavaScript and TypeScript (and in other languages as well).

let isDone: boolean = false;
Copy the code

digital

Like JavaScript, all numbers in TypeScript are floating point numbers. The type that writes only floating-point numbers is number. In addition to supporting decimal and hexadecimal literals, TypeScript also supports binary and octal literals introduced in ECMAScript2015.

let decLiteral: number = 6;
let hexLiteral: number = 0xf00d; 
let binaryLiteral: number = 0b1010; 
let octalLiteral: number = 0o744;
Copy the code

string

Another basic operation of a JavaScript program is to process text data on the Web page or server side. As in other languages, we use string to represent the text data type. Like JavaScript, you can use double quotes (“) or single quotes (‘) to represent strings.

let name: string = "bob"; name = "smith";
Copy the code

You can also use template strings, which can define multiple lines of text and inline expressions. The string is surrounded by backquotes (‘) and is embedded in an expression in the form ${expr}

let name: string = `Gene`; 
let age: number = 37; 
let sentence: string = `Hello, my name is ${ name }.
I'll be ${ age + 1 } years old next month.`;
Copy the code

This has the same effect as defining sentence as follows:

let sentence: string = "Hello, my name is " + name + ".\n\n" + 
"I'll be " + (age + 1) + " years old next month.";
Copy the code

An array of

TypeScript manipulates array elements just like JavaScript. There are two ways to define an array. First, the element type can be followed by [] to represent an array of elements of that type:

An array of

TypeScript manipulates array elements just like JavaScript. There are two ways to define an array. First, the element type can be followed by [] to represent an array of elements of that type:

let list: number[] = [1.2.3];
Copy the code

The second way is to use Array generics, Array< element type > :

let list: Array<number> = [1.2.3];
Copy the code

Tuples Tuple

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]; 
// Initialize it
x = ['hello'.10]; // OK 
// Initialize it incorrectly 
x = [10.'hello']; // Error
Copy the code

When accessing an element with a known index, we get the correct type:

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

When accessing an out-of-bounds element, the union type is used instead:

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
Copy the code

Union types are an advanced topic that we will discuss in a later chapter.

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 Color {Red, Green, Blue}
let c: Color = Color.Green;
Copy the code

By default, elements are numbered from 0. You can also manually specify the values of the members. For example, let’s change the above example to number from 1:

enum Color {Red = 1, Green, Blue} 
let c: Color = Color.Green;
Copy the code

Alternatively, all manual assignments are used:

enum Color {Red = 1, Green = 2, Blue = 4} 
let c: Color = Color.Green;
Copy the code

One of the conveniences provided by an enumerated type is that you can refer to its name by enumeration. For example, if we know that the value is 2, but are not sure which name in Color it maps to, we can look for the corresponding name:

enum Color {Red = 1, Green, Blue} 
let colorName: string = Color[2]; 
console.log(colorName); // Display 'Green' because its value is 2 in the code above
Copy the code

Any

Sometimes we want to specify a type for variables whose type is not known at programming time. These values may come from dynamic content, such as user input or third-party code libraries. In this case, we don’t want the type checker to check these values and just pass them through compile-time checks. We can then mark these variables with type any:

let notSure: any = 4; 
notSure = "maybe a string instead"; 
notSure = false; // okay, definitely a boolean
Copy the code

The any type is useful when rewriting existing code, allowing you to optionally include or remove type checking at compile time. You might think that Object has a similar function, just as it does in other languages. But a variable of type Object only allows you to assign arbitrary values to it – but not to call arbitrary methods on it, even if it does have them:

let notSure: any = 4; 
notSure.ifItExists(); // okay, ifItExists might exist at runtime 
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check) 
let prettySure: Object = 4; 
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
Copy the code

The any type is also useful when you only know part of the data type. For example, you have an array that contains different types of data:

let list: any[] = [1.true."free"];
list[1] = 100;
Copy the code

Void

In a way, void is like the opposite of any; it means there is no type at all. When a function returns no value, you usually see the return type void:

function warnUser() :void { 
    console.log("This is my warning message"); 
}
Copy the code

Declaring a void variable doesn’t do much good, because you can only assign undefined and null to it:

let unusable: void = undefined;
Copy the code

Null, and Undefined

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

// Not much else we can assign to these variables!
let u: undefined = undefined; 
let n: null = null;
Copy the code

By default null and undefined are subtypes of all types. This means that you can assign null and undefined to variables of type number.

However, when you specify strictNullChecks, null and undefined can only be assigned to void and their respective checks. This avoids many common problems. Maybe somewhere you want to pass in a string or null or undefined, you can use the combined type string | null | is undefined. Again, we’ll cover union types later.

Note: We encourage the use of strictNullChecks wherever possible, but in this manual we assume that this flag is closed.

Never

The never type represents the types of values that never exist. For example, the never type is the return type of function expressions or arrow function expressions that always throw an exception or have no return value at all; Variables can also be of type never, when they are bound by type protection that is never true.

The never type is a subtype of any type and can be assigned to any type; However, no type is a subtype of never or can be assigned to a type of never (except never itself). Even any cannot be assigned to never.

Here are some functions that return type never:

// 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

Object

Object represents a non-primitive type, that is, a type other than number, string, Boolean, symbol, NULL, or undefined.

Use the object type to better represent apis like Object.create. Such as:

declare function create(o: object | null) :void;
create({ prop: 0 }); // OK 
create(null); // OK 
create(42); // Error
create("string"); // Error 
create(false); // Error 
create(undefined); // Error
Copy the code

Types of assertions

Sometimes you’ll find that you know more about a value than TypeScript does. Usually this happens when you clearly know that an entity has a more exact type than its existing type.

Type assertions are a way of telling the compiler, “Trust me, I know what I’m doing.” Type assertion is like conversion in other languages, but without special data checking and deconstruction. It has no run-time impact, only at compile time. TypeScript assumes that you, the programmer, have done the necessary checks.

Type assertions come in two forms. The first is the Angle bracket syntax:

let someValue: any = "this is a string"; 
let strLength: number = (<string>someValue).length;
Copy the code

The other is the as syntax:

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Copy the code

The two forms are equivalent. Which to use is mostly a matter of personal preference; However, when you use JSX in TypeScript, only AS syntax assertions are allowed.

aboutlet

You may have noticed that we used the let keyword instead of the familiar JavaScript keyword var. The let keyword is a new concept in JavaScript that TypeScript implements. We’ll cover this in more detail later, but many common problems can be solved by using lets, so use lets instead of var whenever possible.