Introduction to the

TypeScript is a superset of JavaScript that supports the ECMAScript 6 standard. TypeScript a free and open source programming language developed by Microsoft. TypeScript is designed for large applications that can be compiled into pure JavaScript that runs in any browser.

With a brief overview of TypeScript’s background, this article will provide you with a quick and easy way to demystify TypeScript and get your hands dirty with the TS project!

Audience: front-end developers who are familiar with the JavaScript language but have no knowledge or experience with TypeScript.

Everything has a type!

Compared to JavaScript, TS introduces a type system that provides static type checking at compile time through type annotations. That is, TS will check all data for valid types at compile time and throw exceptions for potential type errors, rather than waiting for the project to go live and cause an online accident!

With ts’s type system, our applications will be more standardized, robust, and scalable and maintainable for large, complex applications.

What is a type system?

In the computer world, all data have type, data in our code corresponding to the variable, constant, that is to say: variable, constant should have type!

A type determines which properties and methods a variable has. Accessing properties or methods that a type does not have will result in an error.

For example, we define and use variables in JS like this:

var a = 1
a = 'hello'
a = false
Copy the code
  • The code defines a variable, a, whose initial value is the number 1, and its data type is numeric.
  • On the second line, however, we reassign the string hello to A, and its data type becomes a string!
  • On the third line of code, we assign a Boolean value againfalseAnd now its data type is againBoolean type.

This is because JavaScript is a dynamically typed scripting language, and the same variable can be used as different data types. While this is flexible in practice, it can also lead to disaster!

When we access a variable’s properties and methods, the code editor doesn’t immediately check its data type, because its type can only be determined at run time!

Imagine that in your project, you provide a function that takes a string argument. Inside the function, you get the number of characters for that argument. However, when the caller gives you a numeric argument, the program crashes! (This error only occurs at runtime)

function getStringLength (str) {
    var len = str.length;
    return len;
}
let a = 6;
getStringLength(a); // error: The length attribute does not exist for numeric type A!
Copy the code

Therefore, TS solves this problem well, because: Everything has a type!

Again, let’s see how TS is implemented, regardless of the syntax.

function getStringLength (str: string) :number {
    var len:number = str.length;
    return len;
}
let a:number = 6;
const count: number = getStringLength(a); // error: failed to compile!
Copy the code

The above code will be in your editor directly error, cannot compile! The great thing about type systems is that ts already anticipates potential errors during development!

Let’s examine this code:

  1. Let’s first look at the function’s entry parameter STR, which is followed by a colon, followed by a colonstringIn ts, the variable STR is a string! This means that STR only accepts string values and nothing else!
  2. functiongetStringLengthIs followed by a colon andnumber, this is represented in TS, and this function will return onenumberType, if the function does not return any datavoidSaid.
  3. The last two lines of code define onenumberType a and call the function with a as an argumentgetStringLength, the compiler will report an error! The reason is delta functiongetStringLengthMust be of type string!

As you can see, in TS, everything needs an explicit data type, whether it is a function entry parameter, variable, constant, or function return value. The syntax for defining a type is a colon followed by the data type.

Underlying data types

Ts provides the following basic data types. The syntax for defining variable types is: Write the type after a colon, for example, let userName: string;

type Syntax keyword
string string
The numerical number
Boolean value boolean
A null value void
Any value any
undefined undefined
null null

Note: Keywords for all data types begin in lower case!

Any arbitrary value

Although TS provides an arbitrary value type, any, which is used to represent data that cannot be typed explicitly at programming time, in practice we should try to avoid using it! Because it has the same problem as JS, which is that you can’t do type checking at compile time.

Take a look at this example:

let a:any = 1;
let count:number = a.length; // error: An error is reported when the value type does not have the length attribute
Copy the code

The above code does not raise an error in the editor because a’s data type is any, which means it can be of any type, so the type-checking system can’t figure out exactly what properties or methods it has.

The joint type

In real development, it is often impossible to determine what type a variable is, but it can be expected to be one of several types, such as code, the variable used to receive the status code returned by the network interface. It can be a number or a string.

In this case, the union type is used, as follows:

let code: number | string;
code = 0
code = '0'
code = false // error: the combination type of code can only be string or number, not Boolean
Copy the code
  • As shown in the code above, a vertical line separates multiple types to indicate that the variable is a union type.
  • Variables of union type can only be assigned to defined types, not undefined types. As in the example above, code can only assign strings or numbers, but not booleans!
  • Once a value is assigned to a union type, only the properties or methods of the assigned type can be accessedCode, for example, is not accessible if it is assigned to 0code.lengthBecause code is now explicitly numeric.

Types of assertions

In the example below, when you define a joint type for a function’s input parameter, you may need to get a certain type of attribute in your code and use type assertion.

The syntax for type assertions is as, e.g. Val as string

function checkData (code: string | number) :boolean {
    if (code as string) {
        return (code as string) === '0'
    } else {
        return (code as number) === 0}}Copy the code

A type assertion tells the compiler to check the variable as a type. Note: Type assertions can only be types defined in the union type.

interface

An interface is a description of the characteristics of a key-value pair structure (Object type in JS). We can use {} to define any structure of data in JS, but it also brings great risks, as shown in the following example:

let user = {
    name: 'zhangsan'.age: 33.school: 'bei jing da xue'
}
 
user.info.message // error: Run error! Because the User object does not have an info attribute
user.age.length // error: Run error! Because the age attribute of the User object is a numeric type, there is no length attribute
Copy the code

Errors like these account for a large percentage of front-end problems, because in JS objects, we are completely unpredictable when accessing their properties or methods, relying on the caller to pass the correct data, which greatly reduces the robustness of the application.

Let me see how to solve this problem in TS!

Interface Definition

In the following code, we define a User interface. I recommend that you think of the interface as a custom type. That is, in addition to the basic data types provided by TS, we can customize data types with complex structures.

interface User {
    name: string;age: number;isAdmin: boolean;
}
Copy the code

Interface definition syntax: interface < interface name > {[attribute name]: < attribute type >; }

Note: The interface definition specification requires that all interface names be capitalized. (In the Java language, any interface starts with an I, but I don’t recommend it in TS.)

As shown in the code, the User interface specifies the characteristics of a data structure. If we think of it as a data type, all data of type User must have the following requirements:

  1. Must have a name attribute and must be a string;
  2. Must have an age attribute and must be numeric;
  3. Must have an isAdmin attribute and must be a Boolean value type;
  4. No more attributes can appear except the three above!

With these constraints, we can easily define and use such “rigorous” data.

Use of interfaces

With the following code, we define a variable of type User and assign it a value:

let user: User = {
    name: 'zhangsan'.age: 33.isAdmin: false
};
user.age = 32;
user.name = 6; // error-name must be a string
user.school = 'bei da'; // The error-user interface does not have the school attribute
Copy the code
  • As you can see, the variable user we defined is written after the colonUser, which means that the variable user is aUserType of data, thenIt must conform to the characteristics specified by the User! That is, the name, age, and isAdmin attributes must be included.
  • And the data type for each attribute must also matchUserThe provisions of the. If any of the features do not match, the compiler will report an error!

With this “mandatory” constraint, we can define some of our own data interfaces (custom data types) to ensure that users can safely transfer data during application development.

Optional attribute

As we know from the above, the interface defines a set of key-value pair characteristics of the data structure. When we use an interface to define variables and assign values, we must contain all attributes. However, in practical development, some data attributes may not be necessary, so they are optional.

In TS, this can be done with optional attributes, as shown in the following code:

interface User {
    name: string;age: number;isAdmin: Boolean; school? : string;This is an optional attribute
}
 
 
let user: User = {
    name: 'zhangsan'.age: 33.isAdmin: false
} // The program will not report an error because school is an optional property and can be left unassigned.
Copy the code

As shown above, the school attribute is followed by a question mark, which indicates that the school attribute is optional when the User data type is assigned.

Any attribute

In other cases, when we define an interface, we may not know what attributes the actual data has beyond the known attribute list, so we cannot strictly define such data characteristics.

Thus, TS provides definitions for arbitrary attributes, as shown in the following code:

interface User {
    name: string;age: number;isAdmin: Boolean; school? : string; [propName: string]: any;// This is an arbitrary property
}
 
 
let user: User = {
    name: 'zhangsan'.age: 33.isAdmin: false.sex: 1
} // The program does not report an error, because User contains any attributes, so assigning sex is ok.
Copy the code

Syntax for any property: [propName: string]: any, note: The data type of any property must be any!

other

(Arrays, functions, enumerations, and generics will be updated in a future article, so stay tuned!)

The first article of the Nuggets, please support!