• Chinese version of TypeScript Tutorial – Project introduction
  • TypeScript Tutorial Chinese version – Section 0. preface
  • TypeScript Tutorial Chinese version – Section 1. An introduction to
  • TypeScript Tutorial Chinese version – Section 2. Basic types of
  • TypeScript Tutorial Chinese version – Section 3. Control flow statement
  • TypeScript Tutorial Chinese – Section 4. function
  • TypeScript Tutorial Chinese version – Section 5. class
  • TypeScript Tutorial Chinese version – Section 6. interface
  • TypeScript Tutorial Chinese version – Section 7. High-level types
  • TypeScript Tutorial Chinese version – Section 8. The generic
  • TypeScript Tutorial Chinese version – Section 9. The module
  • Chinese version of TypeScript Tutorial – Section 10.node.js

Section 2. Basic types

type

The original address

In this tutorial, you’ll learn about TypeScript types and their uses.

What are types in TypeScript

In TypeScript, a type conveniently describes the properties and methods that a value has. A value is anything that can be assigned to a variable, such as a number, string, array, object, or function.

Take a look at the following values:

'Hello'
Copy the code

When you look at this value, you say it’s a string, and this value has properties and methods that strings have. For example, the ‘Hello’ value has an attribute named length, which returns the number of characters the string has:

console.log('Hello'.length); / / 5
Copy the code

It also has many methods, such as match(), indexOf() and toLocaleUpperCase(), for example:

console.log('Hello'.toLocaleUpperCase()); // HELLO
Copy the code

When looking at the value of ‘Hello’, it is inconvenient to describe it by listing all its properties and methods, but it is much simpler and more efficient to describe a value by type.

In this case, you indicate that ‘Hello’ is a string, and you know that you can use all of the properties and methods that a string has on the ‘Hello’ value.

In summary, in TypeScript:

  • A type is a label that describes the attributes and methods that a value has;
  • Each value has a type.

Types in TypeScript

TypeScript inherits JavaScript’s built-in types, which can be classified as:

  • The original type
  • Object type

The original type

Primitive types in TypeScript are listed below:

The name describe
string Represents text type data
digital Numerical value
Boolean value There aretrueValues andfalse
null There is one value: null
undefined There is one value: undefined, which is the default value of an uninitialized variable
symbol Represents a unique constant value

Object type

Object types include functions, arrays, and classes. Later you’ll learn how to create custom object types.

The role of types in TypeScript

The main functions of TypeScript types are as follows:

  • First, the TypeScript compiler uses types to analyze errors in code.
  • Second, types help you understand what values a variable is associated with.

Examples of TypeScript types

The following example uses the querySelector() method to select

elements:

const heading = document.querySelector('h1');
Copy the code

The TypeScript compiler knows that heading is of type HTMLHeadingElement:

The following is a list of properties and methods accessible to the heading variable of type HTMLHeadingElement:

The TypeScript compiler displays an error message if you try to access properties and methods that do not exist on values:

summary

  • Every value in TypeScript has a type;
  • A type is a label that describes the attributes and methods that a value has;
  • The TypeScript compiler uses types to analyze your code to find bugs or errors.

Type annotation

The original address

In this tutorial, you’ll learn about TypeScript type annotations.

What are type annotations in TypeScript

TypeScript uses type annotations to explicitly type identifiers such as variables, functions, and objects. Type annotation syntax in TypeScript adds the: type identifier after the identifier, where type can be any valid type. Once an identifier is declared as a type, it can only be used as that type, and the TypeScript compiler throws an error if it is used as another type.

Type comments in variables and constants

Here is the syntax for specifying type comments for variables and constants:

let variableName: type;
let variableName: type = value;
const constantName: type = value;
Copy the code

In this syntax, type comments are followed by variable or constant names and preceded by a colon (:).

The variables in the following example are annotated with numeric types:

let counter: number;
Copy the code

After that, you can only assign one number to the counter variable:

counter = 1;
Copy the code

If you assign a string to the variable counter, you’ll get an error message:

let counter: number;
counter = 'Hello'; // compile error
Copy the code

Error message:

Type '"Hello"' is not assignable to type 'number'.
Copy the code

You can initialize a variable while adding a type comment to it in a statement, as follows:

let counter: number = 1;
Copy the code

In this example, we initialized the counter variable to 1 when we annotated it with a numeric type.

Here is an example of adding comments for other primitive types:

let name: string = 'John';
let age: number = 25;
let active: boolean = true;
Copy the code

In this example, the name variable is annotated as a string type, the age variable as a number type, and the active variable as a Boolean type

Type annotation examples

An array of

To add a type comment to a variable of array type, use a specific type: it is followed by square brackets: type[] identifies:

let arrayName: type[];
Copy the code

For example, the following example declares an array of strings:

let names: string[] = ['John'.'Jane'.'Peter'.'David'.'Mary'];
Copy the code

object

To specify a type for an object, use the object type annotation as follows:

let person: {
  name: string;
  age: number;
};

person = {
  name: 'John'.age: 25};/ / legal
Copy the code

In this example, the Person object accepts only objects with two specified properties: a property of type String named name and a property of type number named age.

Function parameters and return types

Here is a function comment syntax with parameter type comments and return type comments:

let greeting: (name: string) = > string;
Copy the code

In this example you can assign a function to greeting that takes an argument of type string and returns a string:

greeting = function (name: string) {
  return `Hi ${name}`;
};
Copy the code

The following example throws an error message because the function assigned to the greeting variable does not match its function type annotation:

greeting = function () {
  console.log('Hello');
};
Copy the code

Error message:

Type '() => void' is not assignable to type '(name: string) => string'. Type 'void' is not assignable to type 'string'.
Copy the code

summary

  • Use the syntax as: [type]To explicitly type a variable, function, or function return value.

Type inference

The original address

In this tutorial, you’ll learn about type inference in TypeScript

Type inference describes how TypeScript infer the type of a variable when you don’t add type annotations to it.

Basis of type inference

When you declare a variable, you can use a type annotation to specify a type for the variable, as follows:

let counter: number;
Copy the code

When you initialize the counter variable to a number, TypeScript infer that counter is of type number, as follows:

let counter = 0;
Copy the code

It is equivalent to the following:

let counter: number = 0;
Copy the code

Similarly, when you assign a value to a function parameter, TypeScript extrapolates the type of the parameter to the default value, such as:

function setCounter(max = 100) {
  // ...
}
Copy the code

In this example, TypeScript infer that the Max parameter is of type number. Similarly, TypeScript deduces that the following increment() function returns a value of type number:

function increment(counter: number) {
  return counter++;
}
Copy the code

It is equivalent to the following example:

function increment(counter: number) :number {
  return counter++;
}
Copy the code

Best generic type algorithm

Consider the following statement:

let items = [1.2.3.null];
Copy the code

To deduce the type of the Items variable, TypeScript considers the type of each element in the array. TypeScript uses the best generic type algorithm to analyze each candidate type and ultimately selects the type that is compatible with all of the candidates as the type of the variable.

In this example, TypeScript chooses the numeric array type (number[]) as the best generic type. If you go to the items array, a string is added to the TypeScript put items variable type inference for Numbers and strings array types, namely (number | string) [].

let items = [0.1.null.'Hi'];
Copy the code

When TypeScript can’t find the best generic type, it returns an associative array type, like this:

let arr = [new Date(), new RegExp('d+')];
Copy the code

In this case, the TypeScript inference arr variable of type (RegExp | Date) [].

Context type

TypeScript uses positional context to infer the type of a variable, a mechanism called context typing, as follows:

document.addEventListener('click'.function (event) {
  console.log(event.button); //
});
Copy the code

In this case, because the event parameter is in the click event, TypeScript knows that it is an instance of MouseEvent.

However, when you change a click event to a Scroll event, TypeScript throws an error message:

document.addEventListener('scroll'.function (event) {
  console.log(event.button); // compiler error
});
Copy the code

Error message:

Property 'button' does not exist on type 'Event'. (2339).Copy the code

TypeScript knows that in this case event is no longer an instance of MouseEvent but an instance of UIEvent. Since UIEvent has no button property, TypeScript throws an error message when accessing the Button property of MouseEvent instances.

Context types can be found in many situations, such as function call parameters, type assertions, object and array members, return statements, and right-hand assignments.

Type inference vs type annotation

The following shows the difference between type inference and type annotation:

Type inference Type annotation
TypeScript guesses the type of a variable Explicitly tell TypeScript the type of a variable

So, when should you use type inference and when should you use type annotation? In fact, you should use type inference whenever possible, and only use type annotations in the following situations:

  • When declaring a variable but assigning it a value later;
  • When you want the type of a variable not to be inferred;
  • When you need to know the type of a function whose return type is any.

summary

  • Type inference occurs when you initialize the value of a variable, set parameter defaults, and determine the return value type of a function.
  • TypeScript uses the best generic type algorithm to select the best candidate type compatible with all variable types;
  • TypeScript also uses context types to infer the type of a variable based on its location.

Numeric types

The original address

In this tutorial, you’ll learn about digital data types in TypeScript.

All numbers in TypeScript are either floating point numbers, which are large integers, and floating point numbers are of type number and large numbers are of type Bigint.

Numeric types

The following example shows how to declare a variable that holds a floating point number:

let price: number;
Copy the code

Or you can initialize the price variable to a number:

let price = 9.95;
Copy the code

Like JavaScript, TypeScript supports decimal, hexadecimal, binary, and octal numeric literals.

Decimal digit

Some decimal numbers are shown below:

let counter: number = 0;
let x: number = 100.y: number = 200;
Copy the code

Binary digit

The binary digits are of the form: a leading 0 followed by a lowercase or uppercase B, such as 0b or 0b:

let bin = 0b100;
let anotherBin: number = 0b010;
Copy the code

Note that either 0b or 0b must be followed by the number 0 or 1.

Octal digit

Octal digits are of the form: a leading 0 followed by the letter O (since ES2015), of the form 0O. The number after 0o ranges between the number 0 and the number 7.

let octal: number = 0o10;
Copy the code

A hexadecimal number

The hexadecimal number is in the form of a leading 0 followed by a lowercase or uppercase X (0x or 0x). The number after 0x must be in the range of (0123456789ABCDEF), as follows:

let hexadecimal: number = 0xa;
Copy the code

JavaScript has a Number type (note the uppercase N). This type represents an unprimitive, encapsulated object type, and is not used in TypeScript whenever possible.

Large integer

A large integer represents all integers greater than 2^ 53-1. A large integer ends with an n character, as follows:

let big: bigint = 9007199254740991n;
Copy the code

summary

  • All numbers in TypeScript, ornumberFloat of type, thenbigintA large integer of type;
  • Avoid using if possibleNumberType.

String type

The original address

In this tutorial, you’ll learn about TypeScript string data types.

As in JavaScript, strings are wrapped in double quotes (“) or single quotes (‘) in TypeScript:

let firstName: string = 'John';
let title: string = 'Web Developer';
Copy the code

TypeScript also supports template string syntax that wraps characters in backquotes (‘). Template strings allow you to create multi-line strings, as well as string interpolation.

The following example shows how to create a multi-line string using backquotes (‘) :

let description = `This TypeScript string can
span multiple
lines
`;
Copy the code

The string interpolation feature allows you to embed variables in strings like this:

let firstName: string = `John`;
let title: string = `Web Developer`;
let profile: string = `I'm ${firstName}.
I'm a ${title}`;

console.log(profile);
Copy the code

Output:

I'm John.
I'm a Web Developer.
Copy the code

summary

  • In TypeScript, all strings arestringType;
  • Like JavaScript, TypeScript uses double quotes ("), single quotation mark (') or enclose the string with backquotes (‘).

Boolean value type

The original address

In this tutorial, you’ll learn about Boolean data types in TypeScript.

Boolean types in TypeScript have two values: true and false, and are one of TypeScript’s primitive types, as shown below:

let pending: boolean;
pending = true;
// after a while
// ..
pending = false;
Copy the code

JavaScript has a type that represents unprimitive, encapsulated objects called Boolean types. Boolean types start with an uppercase B character and are not the same as Boolean types, so we try to avoid using Boolean types.

Object type

The original address

In this tutorial, you’ll learn about object data types in TypeScript and how to write object type declarations more accurately.

Introduction to object types in TypeScript

The object type in TypeScript represents all values that are not primitive types. Primitive types in TypeScript include:

  • number
  • bigint
  • string
  • boolean
  • null
  • undefined
  • symbol

The following example shows how to declare a variable that holds an object:

let employee: object;

employee = {
  firstName: 'John'.lastName: 'Doe'.age: 25.jobTitle: 'Web Developer'};console.log(employee);
Copy the code

Output:

{
  firstName: 'John',
  lastName: 'Doe',
  age: 25,
  jobTitle: 'Web Developer'
}
Copy the code

If you assign a primitive type to the Employee object, you will get an error message:

employee = 'Jane';
Copy the code

Error message:

error TS2322: Type '"Jane"' is not assignable to type 'object'.
Copy the code

The Employee object is an Object type with a fixed list of attributes. If you try to access attributes that do not exist in the Employee object, you will get an error message:

console.log(employee.hireDate);
Copy the code

Error message:

error TS2339: Property 'hireDate' does not exist on type 'object'.
Copy the code

Note: The above statement works fine in JavaScript and returns undefined.

To explicitly specify the attributes of the Employee object, first define the Employee object using the following syntax:

let employee: {
  firstName: string;
  lastName: string;
  age: number;
  jobTitle: string;
};
Copy the code

Then you assign an object with all of the above attributes to the Employee object:

employee = {
  firstName: 'John'.lastName: 'Doe'.age: 25.jobTitle: 'Web Developer'};Copy the code

It is also possible to combine the two grammars in a single statement, as follows:

let employee: {
  firstName: string;
  lastName: string;
  age: number;
  jobTitle: string;
} = {
  firstName: 'John'.lastName: 'Doe'.age: 25.jobTitle: 'Web Developer'};Copy the code

object vs Object

It’s important to understand the difference between TypeScript’s other type, called Object, whose character O is capitalized. The object type represents all non-primitive values, and the object type describes the functions that all objects have. For example, the Object type has toString() and valueOf() methods that can be accessed by any Object.

Empty type {}

TypeScript has another type called null, represented by {}, which is very similar to the object type. The null type {} describes an object that has no attributes of its own. TypeScript issues a compile-time error if you try to access an attribute of an object of this type:

let vacant: {};
vacant.firstName = 'John';
Copy the code

Error message:

error TS2339: Property 'firstName' does not exist on type '{}'.
Copy the code

However, all properties and methods defined on the Object type can be accessed through the stereotype chain:

let vacant: {} = {};

console.log(vacant.toString());
Copy the code

Output:

[object Object]
Copy the code

summary

  • In the TypeScriptobjectType represents all values of non-primitive types;
  • ObjectA type describes the functions that all objects have;
  • Empty type{}Describes an object that has no attributes of its own.

An array type

The original address

In this tutorial, you’ll learn about array types in TypeScript and some of its basic operations.

An introduction to array types in TypeScript

Array in TypeScript is an ordered list of data. You can declare an array of values of a specified type using the following syntax:

let arrayName: type[];
Copy the code

An array of strings is declared as follows:

let skills: string[];
Copy the code

You can add one or more strings to an array as follows:

skills[0] = 'Problem Solving';
skills[1] = 'Programming';
Copy the code

We can also add elements to an array using push() :

skills.push('Software Design');
Copy the code

In the following example, declare and assign an array of strings to the skills variable:

let skills = ['Problem Sovling'.'Software Design'.'Programming'];
Copy the code

In this example, TypeScript concludes that the Skills array is an array of strings equivalent to:

let skills: string[];
skills = ['Problem Sovling'.'Software Design'.'Programming'];
Copy the code

When you specify an array type, TypeScript prevents you from adding incompatible values to the array. The following example throws an error:

skills.push(100);
Copy the code

Because we’re trying to add a number to the string array.

Error message:

Argument of type 'number' is not assignable to parameter of type 'string'.
Copy the code

When extracting elements from an array, TypeScript does type inference, as shown below:

let skill = skills[0];
console.log(typeof skill);
Copy the code

Output:

string
Copy the code

In this example, we extract the first element in the Skills array and assign it to the Skill variable. TypeScript extrapolates the skill variable’s type to string because the elements in the string array are strings.

Array properties and methods in TypeScript

Arrays in TypeScript have access to all the properties and methods in JavaScript arrays, such as the length attribute to get the number of elements in the array:

let series = [1.2.3];
console.log(series.length); / / 3
Copy the code

You can also use all of the array methods in JavaScript, such as forEach(), map(), reduce(), and filter(), as follows:

let series = [1.2.3];
let doubleIt = series.map((e) = > e * 2);
console.log(doubleIt);
Copy the code

Output:

[2, 4, 6]Copy the code

Stores values of mixed types

Here’s how to declare an array that stores both strings and numbers:

let scores = ['Programming'.5.'Software Design'.4];
Copy the code

In this case, the TypeScript scores array inference as (string | number) [] type, it and this example is equivalent to:

let scores: (string | number) []; scores = ['Programming'.5.'Software Design'.4];
Copy the code

summary

  • In TypeScript, an array is an ordered list of data that can store values of mixed types;
  • Declares an array of the specified type that you can uselet arr: type[]This syntax.

A tuple type

The original address

In this tutorial, you’ll learn about the tuple type in TypeScript and how to use it.

An introduction to tuple types in TypeScript

Tuples work like array types, but with some additional constraints:

  • The number of elements in a tuple is fixed;
  • The types of elements within an element are known, and they need not all be the same.

For example, a tuple can be used to represent a value of the string and number types:

let skill: [string.number];
skill = ['Programming'.5];
Copy the code

The order of values in a tuple is very important. If you set the order of values in a tuple to [5, “Programming”], you will get an error:

let skill: [string.number];
skill = [5.'Programming'];
Copy the code

Error message:

error TS2322: Type 'string' is not assignable to type 'number'.
Copy the code

In summary, it is a good practice to use tuples to store data that has a particular order and is related to each other. For example, a tuple can be used to define an RGB color value that always takes the form of three digits:

(r,g,b)
Copy the code

As follows:

let color: [number.number.number] = [255.0.0];
Copy the code

Color [0], color[1], and color[2] map to Red, Green, and Blue color values, respectively.

Optional tuple elements

Starting with TypeScript 3.0, tuples can be created using question marks (?). Suffixes to specify optional elements. For example, an RGBA tuple can be defined using an optional alpha channel value:

let bgColor, headerColor: [number.number.number.number? ] ; bgColor = [0.255.255.0.5];
headerColor = [0.255.255];
Copy the code

Note: RGBA uses the Red, Green, Blue, and alpha models to define colors, and alpha specifies the transparency of colors.

summary

  • A tuple is an array with a fixed number of known element types.

Enumerated type

The original address

In this tutorial, you’ll learn about TypeScript’s enumerated types and how to use them more efficiently.

What is enumeration

Enumerations are combinations of named constant values. Enums represent enumerations of types. Follow these steps to define enumerations:

  • First, write the variable name inenumAfter the keyword;
  • Then, you define the constant values in the enumeration.

Here is the syntax for defining enumerations:

enumname {constant1, constant2, ... };Copy the code

In this syntax, constant1, constant2, etc., are called members of enumerations.

Examples of enumeration types in TypeScript

The following example creates an enumeration representing all months of the year:

enum Month {
  Jan,
  Feb,
  Mar,
  Apr,
  May,
  Jun,
  Jul,
  Aug,
  Sep,
  Oct,
  Nov,
  Dec,
}
Copy the code

In this case, the enumeration is called Month, and its constant values are Jan, Feb, Mar, and so on.

Let’s declare a function that uses the Month enumeration type as the type of the argument Month:

function isItSummer(month: Month) {
  let isSummer: boolean;
  switch (month) {
    case Month.Jun:
    case Month.Jul:
    case Month.Aug:
      isSummer = true;
      break;
    default:
      isSummer = false;
      break;
  }
  return isSummer;
}
Copy the code

This function can be called like this:

console.log(isItSummer(Month.Jun)); // true
Copy the code

This example uses constant values in enumerations, such as Jan, Feb, Mar, and so on, instead of values such as 1, 2, and 3, to make the code more legible.

How do enumerations in TypeScript work

It is a good practice to use enumerated constant values in your code. However, the following example passes a number instead of an enumeration value to isItSummer(), which also works:

console.log(isItSummer(6)); // true
Copy the code

This example uses a number (6) instead of the enumeration constant value in Month, which also works.

Check the Javascript code generated by the Month enumeration below:

var Month;
(function (Month) {
  Month[(Month['Jan'] = 0)] = 'Jan';
  Month[(Month['Feb'] = 1)] = 'Feb';
  Month[(Month['Mar'] = 2)] = 'Mar';
  Month[(Month['Apr'] = 3)] = 'Apr';
  Month[(Month['May'] = 4)] = 'May';
  Month[(Month['Jun'] = 5)] = 'Jun';
  Month[(Month['Jul'] = 6)] = 'Jul';
  Month[(Month['Aug'] = 7)] = 'Aug';
  Month[(Month['Sep'] = 8)] = 'Sep';
  Month[(Month['Oct'] = 9)] = 'Oct';
  Month[(Month['Nov'] = 10)] = 'Nov';
  Month[(Month['Dec'] = 11)] = 'Dec';
})(Month || (Month = {}));
Copy the code

You can print the Month variable on the console:

{
  '0': 'Jan'.'1': 'Feb'.'2': 'Mar'.'3': 'Apr'.'4': 'May'.'5': 'Jun'.'6': 'Jul'.'7': 'Aug'.'8': 'Sep'.'9': 'Oct'.'10': 'Nov'.'11': 'Dec'.Jan: 0.Feb: 1.Mar: 2.Apr: 3.May: 4.Jun: 5.Jul: 6.Aug: 7.Sep: 8.Oct: 9.Nov: 10.Dec: 11
}
Copy the code

It’s clear from the output that TypeScript enumerations are essentially JavaScript objects that declare named properties in them, such as Jan being 0 and Feb being 1, as well as numeric keys and string values representing named constants. That’s why you can pass a number to a function that accepts an enumeration; in other words, an enumeration member is both a number and a defined constant value.

Specifies the value of an enumeration member

TypeScript defines enumeration members’ values based on the order in which they appear in an enumeration definition, such as Jan being 0, Feb being 1, and so on.

Enumeration members can be explicitly specified as follows:

enum Month {
  Jan = 1,
  Feb,
  Mar,
  Apr,
  May,
  Jun,
  Jul,
  Aug,
  Sep,
  Oct,
  Nov,
  Dec,
}
Copy the code

In this example, the Jan constant has a value of 1 instead of 0, Feb has a value of 2, Mar has a value of 3, and so on.

When to use enumerations

Enumerations can be used in the following cases:

  • There is a small and closely related set of fixed values;
  • These values are known at compile time.

For example, you can use enumerations to indicate approval status:

enum ApprovalStatus {
  draft,
  submitted,
  approved,
  rejected,
}
Copy the code

You can then use the ApprovalStatus enumeration as follows:

const request = {
  id: 1.status: ApprovalStatus.approved,
  description: 'Please approve this request'};if (request.status === ApprovalStatus.approved) {
  // Send an email
  console.log('Send email to the Applicant... ');
}
Copy the code

summary

  • Enumerations in TypeScript are collections of constant values;
  • Essentially, an enumeration is a JavaScript object with named attributes declared in the enumeration definition;
  • If you have a small, closely related set of fixed values that are known at compile time, use enumerations by all means

Any type

The original address

In this tutorial, you’ll learn about TypeScript’s any type and how to use it properly in your code.

The any type in TypeScript

Sometimes you need to store a value in a variable, but you don’t know its type at the time you write the code. This unknown value may come from a third-party API or user input. In this case, if you want to skip type checking and allow it to pass at compile time, you can use any, which allows you to assign a value of any type to a variable:

// json may come from a third-party API
const json = ` {" latitude ", 10.11, "longitude" : 12.12} `;

// parse JSON to find location
const currentLocation = JSON.parse(json);
console.log(currentLocation);
Copy the code

Output:

{latitude: 10.11, longitude: 12.12}Copy the code

In this example, the object returned by the json.parse () function is assigned to the currentLocation variable. When you access the properties of the currentLocation variable, TypeScript doesn’t do any type checking:

console.log(currentLocation.x);
Copy the code

Output:

undefined;
Copy the code

In the example above, the TypeScript compiler does not throw any error messages.

TypeScript’s any type provides a way to work with the current javascript-based code base by allowing you to use type detection at compile time. Therefore, you can use the any type to smooth the transition from javascript-based projects to typescript-based projects.

TypeScript implicitly has the any type

If you declare a variable without specifying a type, TypeScript assumes that the variable is of type any. This feature is called type inference. TypeScript basically does inference about variable types, such as:

let result;
Copy the code

In this case, TypeScript does type inference for variables, a feature called implicit typing.

Note: To disable the implicit type feature for any, you need to set the noImplicitAny option in the tsconfig.json file to true. You’ll learn more about the tsconfig.json configuration file in later tutorials.

Any vs object types in TypeScript

let result: any;
result = 10.123;
console.log(result.toFixed());
result.willExist(); //
Copy the code

In this case, the result variable is of type any, so even if the willExist() method does not exist at compile time, the TypeScript compiler does not throw any error when calling it. Because the willExist() function might be available at run time. However, if you change the type of the result variable to object, the TypeScript compiler throws an error:

let result: object;
result = 10.123;
result.toFixed();
Copy the code

Error message:

error TS2339: Property 'toFixed' does not exist on type 'object'.
Copy the code

summary

  • TypeScript anyType allows you to store values of any type, and it tells the compiler not to do type checking;
  • useanyType to store values that are not known at compile time or when a JavaScript project migrates to a TypeScript project.

Void type

The original address

In this tutorial, you’ll learn about the void type in TypeScript and how to use it to represent the return type of a function that doesn’t return any value.

Introduction to the void type in TypeScript

Void means that the value has no type, which is sort of the opposite of any. You can actually use void to indicate the return type of a function that does not return any value, as follows:

function log(message) :void {
  console.log(messsage);
}
Copy the code

It is a good practice to add void to a function or method that does not return any value. You can reap the following benefits:

  • Improved code clarity: You don’t have to read the whole function body to see if it returns anything;
  • Be type safe: you will never return a return type ofvoidType function assigned to a variable.

Note that if you use a variable of type void, you can only assign it undefined, in which case the value of type void is useless, as shown below:

let useless: void = undefined;
useless = 1; // error
Copy the code

If the –strictNullChecks flag is not specified, you can assign null to the Useless variable.

useless = null; // OK if --strictNullChecks is not specified
Copy the code

Never type

The original address

In this tutorial, you’ll learn about the never type in TypeScript, which contains no values.

The never type is a type that contains no value, and for this reason, you cannot assign any value to a variable of type never. In general, you can use the never type to indicate the return type of a function that always throws an error, as follows:

function raiseError(message: string) :never {
  throw new Error(message);
}
Copy the code

The return value of the following function is inferred to be of type never:

function reject() {
  return raiseError('Rejected');
}
Copy the code

A function that contains an infinite loop whose return type is also never looks like this:

let loop = function forever() {
  while (true) {
    console.log('Hello'); }};Copy the code

In this case, the return type of forever() is never.

If you see a function whose return type is never, be sure that this is what you want.

You can also get the never type when you use type protection to shrink the type of a variable so that some condition judgments can no longer be true. As shown below, without the never type, the following function throws an error because not all paths in the code return values:

function fn(a: string | number) :boolean {
  if (typeof a === 'string') {
    return true;
  } else if (typeof a === 'number') {
    return false; }}Copy the code

To make the code effective, you can return a function of type never:

function fn(a: string | number) :boolean {
  if (typeof a === 'string') {
    return true;
  } else if (typeof a === 'number') {
    return false;
  }
  // make the function valid
  return neverOccur();
}

let neverOccur = () = > {
  throw new Error('Never! ');
};
Copy the code

summary

  • neverA type does not contain a value;
  • neverType represents the return type of a function that always throws an error or contains an infinite loop.

The joint type

The original address

In this tutorial, you’ll learn about TypeScript associative typing, which allows you to store one or more different types of values in variables.

An introduction to union types in TypeScript

Sometimes you’ll come across a function that wants to take a number or string value as an argument, like this:

function add(a: any, b: any) {
  if (typeof a === 'number' && typeof b === 'number') {
    return a + b;
  }
  if (typeof a === 'string' && typeof b === 'string') {
    return a.concat(b);
  }
  throw new Error('Parameters must be numbers or strings');
}
Copy the code

In this example, if both arguments are numbers, add evaluates their sum, while if both arguments are strings, add concatenates them into a single string. If neither argument is a number nor a string, add() throws an error message.

The problem with the add() function is that its argument type is any, which means it can be called with arguments that are neither numbers nor strings, which TypeScript accepts. The code will compile successfully, but will throw an error at runtime:

add(true.false);
Copy the code

To solve this problem, you can use TypeScript union types, which allow multiple types to be combined into a single type. The result variable is of type number or string, as follows:

let result: number | string;
result = 10; // OK
result = 'Hi'; // also OK
result = false; // a boolean value, not OK
Copy the code

The value described by a union type can be one of several types, but not just two. Such as number | string | Boolean is a value type, it can be Numbers, string or Boolean value. Going back to the add() example, you can change the type of its argument from any to union:

function add(a: number | string, b: number | string) {
  if (typeof a === 'number' && typeof b === 'number') {
    return a + b;
  }
  if (typeof a === 'string' && typeof b === 'string') {
    return a.concat(b);
  }
  throw new Error('Parameters must be numbers or strings');
}
Copy the code

summary

  • Joint types in TypeScript allow you to store one or more different types of values in variables.

Type the alias

The original address

In this tutorial, you will learn how to use type aliases to give new names to types.

An introduction to TypeScript type aliases

Type aliases allow you to specify new names for existing types. The syntax for type aliases is as follows:

type alias = existingType;
Copy the code

Existing types can be any valid TypeScript type. The following example uses a type alias to specify the new name chars for string:

type chars = string;
let messsage: chars; // same as string type
Copy the code

It is useful to create a type alias for a federated type, as follows:

type alphanumeric = string | number;
let input: alphanumeric;
input = 100; // valid
input = 'Hi'; // valid
input = false; // Compiler error
Copy the code

String literal type

The original address

In this tutorial, you’ll learn about TypeScript’s string literal types, which specify string literals that are type-acceptable.

String literal types allow you to define a type that accepts only a specified string literal. The following example defines a string literal type that accepts only ‘click’ string literals:

let click: 'click';
Copy the code

The click variable is a string literal type that accepts only the string ‘click’. If you assign the string click to the click variable, it is legal:

click = 'click'; // valid
Copy the code

But if you assign another string to the click variable, the TypeScript compiler throws an error message like this:

click = 'dblclick'; // compiler error
Copy the code

Error message:

Type '"dblclick"' is not assignable to type '"click"'.
Copy the code

It is useful to use string literal types to limit the number of string literals that can occur in a variable.

String literal types can be used in conjunction with union types to define a limited, optional set of string literals for variables:

let mouseEvent: 'click' | 'dblclick' | 'mouseup' | 'mousedown';
mouseEvent = 'click'; // valid
mouseEvent = 'dblclick'; // valid
mouseEvent = 'mouseup'; // valid
mouseEvent = 'mousedown'; // valid
mouseEvent = 'mouseover'; // compiler error
Copy the code

It is redundant to use the same string literal type in multiple places. You can avoid this by using type aliases, as shown below:

type MouseEvent: 'click' | 'dblclick' | 'mouseup' | 'mousedown';
let mouseEvent: MouseEvent;
mouseEvent = 'click'; // valid
mouseEvent = 'dblclick'; // valid
mouseEvent = 'mouseup'; // valid
mouseEvent = 'mousedown'; // valid
mouseEvent = 'mouseover'; // compiler error

let anotherEvent: MouseEvent;
Copy the code

summary

  • String literals in TypeScript specify string literals that are type-acceptable;
  • String literal types are used in combination with union types and type aliases to specify that a limited, optional collection of string literals can be accepted.