This article will take a look at typescript, but we’ll see how it’s used in the next article.

What is a TypeScript

TypeScript is a super version of JavaScript that provides a type system and support for ES6.

Install TypeScript and compile Ts files

NPM -g install typescrip installs typescript globallyCopy the code

After installing typescript globally, you can use the TSC command on the terminal. Compile the ts file as follows:

// hello.ts
function foo(name: string) {
    console.log(`Hello ${name}`);
}
foo('Cooper') // Hello Cooper

tsc hello.ts // The corresponding hello.js file is generated after compiling the ts file
Copy the code

TypeScript type checking instructions

Ts only performs static type checking, and if errors are found, an error is reported at compile time. When used in conjunction with Eslint or Tslint, errors are reported during coding.

Basic data types

Declare the type of a variable by adding: type after it.

1. Bolean Boolean value

let isSuccess: boolean = true; / / right
let isSuccess: boolean = new Boolean(1); New generates a Boolean object of type Boolean, which is a constructor, different from the basic data type Boolean
let isSuccess: Boolean = new Boolean(1); / / right
let isSuccess: boolean = Bealean(1); // Returns a basic Boolean value
Copy the code

Note: In typescript, Boolean is a primitive data type, and Boolean is a constructor. Values defined as Boolean cannot be Boolean objects. The same is true for other basic data types

2. Digital

let num: number = 3; / / right
num = '3'; // The value of the variable is number, and the value of the variable is string.
Copy the code

3. The string

let name: string = 'Cooper';
let templetStr: string = `Hello, ${name}`; // ES6 template Character string
Copy the code

4. A null value

In JavaScript there is no concept of Void values, and in TypeScript hollow values are used to indicate that a function has no return value

// Define a function that returns no value
function foo(name: string) :void {
    console.log(name)
}
Copy the code

5. A Null, and Undefined

Variables defined as null can only be assigned to null, and variables defined as undefined can only be assigned to undefined

let u: undefined = undefined;
let m: null = null;
Copy the code

Any value

Variables defined to any value can be assigned to any type. It is possible to access any properties and methods on any type of variable. After declaring a variable of type any, any operation on it returns type any. Untyped variables default to any.

let anyValue: any = '123';
anyValue = 1; // No error is reported because anyValue is of any type
Copy the code

Note: Any is extremely handy, but we recommend not using it in your daily development. TypeScript is designed to write Js code in a more formal way, and if you define it all as any, you lose the point of TypeScript.

Type inference

If the type of a variable is not explicitly specified, TypeScript deduces a type according to the rules of type inference.

let str = 'Cooper';
str = 7; // if STR is a string, it cannot be assigned to a value other than string
Copy the code

The joint properties

Joint type said value can be one of the many types of use dividing line | link between each type

let strOrNumValue: string | number = 'test';
Copy the code
  • Accessing properties and methods of the union type When a variable is defined as the union type, we can access only the public methods and properties of the union type
function getLength(something: string | number) {
    return something.length; The number type does not contain the length attribute
}
function myToString(something: string | number) {
    return something.toString(); // Correct. Both number and string contain toString methods
}
Copy the code
  • When a variable of the union type is assigned, a type is deduced according to the rules of type inference
let something: string | number;
something = 'Cooper';
console.log(something.length) // 5, after something is assigned to a string, it is inferred to be a string, so you can access the length attribute
something = 3
console.log(something.length) / / an error
Copy the code

The type of the object – interface

In TypeScript, we use interfaces to define the type of an object. The interface name usually begins with a capital I and the first letter after the I is capitalized.

interface IPerson {
    name: string;
    age: number;
}
// All attributes of the interface must be of the same type; otherwise, an error is reported
let Cooper: IPerson = {
    name: 'Cooper'.age: 23
}
Copy the code
  • Optional attributes are used to indicate that attributes in an object are optional.
interface IPerson {
    name: string; age? : number;// We use? After attributes. The value is optional
}
// Can only contain the name attribute, age is an optional attribute, but can not add interface undefined attribute
let Cooper: IPerson = {
    name: 'Cooper'
}
Copy the code
  • Any attribute
interface IPerson {
    name: string; age? : string; [propName: string]: string; }let cooper: IPerson = { // true
    name: 'Cooper'.gender: 'male' // Add any attribute gender
}
Copy the code

Note: Once any type is defined, the type of the validation attribute and optional attribute must be a subclass of any attribute type. For example, the above definition is changed to


// An error is reported. Any attribute is string, excluding the number type of the optional attribute
interface IPerson {
    name: string; age? : number; [propName: string]: string; }// Should be changed to the following form
interface IPerson {
    name: string; age? : number; [propName: string]: string | number;// The specific type defined above should also be included in any type
}
Copy the code
  • Read-only Properties Sometimes we want properties that can only be assigned at initialization and cannot be changed later, so we can define them using the readonly keyword
interface IPerson {
    readonly id: number;
    name: string
}
let cooper: IPerson = {
    id: 14202119.name: 'Cooper'
}
cooper.id = 14020120 // The read-only attribute cannot be modified again
Copy the code

The type definition of an array

Arrays can be typed in a variety of ways in TypeScript.

  • Type + brackets
let list: number[] = [1.2.3]; // Each item in the array is of type number
Copy the code
  • Array[T], T is generic
let list: Array<number> = [1, 2, 3];
Copy the code
  • Interface representation
// The key is of type number, that is, the array subscript, and the value is of type number, that is, value
interface INumberArray {
    [index: number]: number
}
let list: INumberArray = [1.2.3]
Copy the code
  • Object array definition
interface IItem = {
    name: string,
    age: number
}
// The array is an object, and the properties of the object must be the same as defined
let list: IItem[] = [
  {
    name: 'Cooper'.age: 23
  },
  {
    name: 'Bob'.age: 23},]Copy the code

Function types

  • How a function is declared
// Function declaration
function foo(name) {
    console.log(name);
}
// Function expression
const mySun = function(x, y) {
    return x + y;
}
Copy the code
  • Functional declarations define types
// Accept two "number" arguments, no less or more arguments allowed, and the return value of the function must be number
function(x: number, y: number) :number {
    return x + y;
}
Copy the code
  • Function expressions define types
let myFun: (x: number, y: number) = > number = function(x: number, y: number) :number {
    return x + y;
}
// The type of the variable on the left side can be omitted, and the left side of the equal sign can be inferred from the type inference, i.e. :
let myfun = function(x: number, y: number) :number {
    return x + y;
}
Copy the code
  • Using interface definitions
interface IMyFun {
    (x: number, y: number): boolean
}
let myFun: IMyFun = function(x: number, y: number): boolean {
    return false;
}
Copy the code
  • Optional and remaining parameters
// Y is optionalfunctionmyFun(x: number, y? : number): number {if (y) {
        returnx + y; }} // Remaining parametersfunctionmyFun(x: number, ... ars: any[]) { console.log(args); } myFun(1, 2,'3'); / / / 2.'3']
Copy the code

Types of assertions

Type assertion is manual (or is it mandatory? . ?). Specifies the type of a variable

  • grammar
< type > variable Variableastype// TSX supports only this mode
Copy the code
function myFun(x: number | string) {
    console.log(<string>x.length); / / the variable x attribute string | number, want to use length attribute directly, you may need to specify the properties of x by type string}Copy the code
  • In particular, when declaring optional parameters, we need to check whether the parameters exist before using them
functionmyFun(x: number, y? : number): number {if(y) { const result = x + y; // Failure to judge will result in an errorreturnresult; }} // Also via assertionsfunctionmyFun(x: number, y? : number): number { const result = x + ! y; / /! That means the change must existreturn result;
}
Copy the code

Note: Type assertion is not a type conversion, and asserting a type that does not exist in a union type will result in an error.

Declaration file

When we introduce a third party module directly into the project and use its methods or attributes, TS will not report an error because these types and methods are undeclared. Because we need to use declaration files to define the types of these properties and methods. Some common third-party modules are already defined by the typescript community as long as they are preceded by @type/ when installed using NPM

npm install express --save// Install the normal Express module
npm install @/types/express --save-dev// Install the Express module with the declaration file, only for local development environment
Copy the code

For infrequently used third-party modules with declaration files that cannot be installed in the typescript community, you can create an index.d.ts file in the project’s root directory and declare it to prevent TS errors.

declare module 'so-utils'; // Declare so-utils as a module to prevent import * from 'so-utils' error
Copy the code

This prevents modules from introducing errors, but there is still no hint for properties and methods defined by the module. To get the full code hint function, you need to define a full declaration file. For the full declaration file name, see the TypeScript Tutorial declaration Files

Built-in objects

There are many defined objects in JavaScript that we can use as defined types.

let bodyDoc: HTMLDocument = document.body; // HTML document flow
Copy the code

Type the alias

We use the type keyword to declare aliases for types

type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver
function getName(n: NameOrResolver): Name {
    if (typeof n === 'string') {
        return n;
    } else {
        returnn(); }}Copy the code

String literal type

String literals are used to restrict the value to one of several string values

type eventName = 'click' |  'scroll' | 'mousemove'
/ / the second parameter event can be to 'click' | 'insensitive' | 'mousemove' one of the three
function handleEvent(ele: Element, event: EventNames) {
    // do something
}
handleEvent(doument.getELementById('hello'), 'scroll'); // true
handleEvent(doument.getELementById('hello'), 'dbclick'); / / an error
Copy the code

reference

  • TypeScript tutorial