The data type

The Booleanboolean

let isDone: boolean = false;
Copy the code

The numericalnumber

All numbers in TypeScript are floating point numbers.

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

stringstring

Use double quotation marks (“) or single quotation marks (‘) to indicate strings.

Use template strings, which can define multiple lines of text and inline expressions. The string is enclosed in backquotes (‘) and embedded in the expression in the form ${expr}.

let name: string = `Gene`;
let sentence: string = `Hello, my name is ${ name }.
Copy the code

A null valuevoid

Used to identify the type of the method return value, indicating that the method does not return a value.

function hello() :void {
    alert("Hello Runoob");
}
Copy the code

Any valueany

Can be assigned to any type.

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

An array ofarray

An element type can be followed by [] to represent an array of elements of that type:

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

Use the Array generic,, Array< element type > :

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

The interface can also be used to describe arrays:

interface NumberArray {
    [index: number] :number;
}
let fibonacci: NumberArray = [1.1.2.3.5];
Copy the code

tuplestuple

The tuple type is used to represent an array with known number and types of elements. The elements need not be of the same type, but the type of the corresponding position needs to be the same.

let x: [string.number];
x = ['Runoob'.1];    // It is running properly
x = [1.'Runoob'];    / / an error
console.log(x[0]);    / / output Runoob
Copy the code

The enumerationenum

Enumeration types are used to define collections of values. This parameter is used when the value is limited to a certain range, such as seven days in a week, and the color is limited to red, green, and blue.

enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};

console.log(Days["Sun"= = =0); // true
console.log(Days["Mon"= = =1); // true
console.log(Days["Tue"= = =2); // true
console.log(Days["Sat"= = =6); // true

console.log(Days[0= = ="Sun"); // true
console.log(Days[1= = ="Mon"); // true
console.log(Days[2= = ="Tue"); // true
console.log(Days[6= = ="Sat"); // true
Copy the code

Enumeration members are assigned numbers increasing from 0, and the enumeration value is inversely mapped to the enumeration name.

Enumerations can be assigned manually. Enumerations that are not manually assigned are incremented by the last one.

If the value of a property is computed, then the member one bit after it must be initialized.

const getValue = () = > {
  return 0
}

enum List {
  A = getValue(),
  B = 2.// The value must be initialized, otherwise the compilation will fail
  C
}
console.log(List.A) / / 0
console.log(List.B) / / 2
console.log(List.C) / / 3
Copy the code

nullandundefined

Null indicates that the object value is missing, and undefined is used to initialize the variable to an undefined value.

Undefined and NULL are subtypes of all types.

never

Never is a subtype of other types, including NULL and undefined, and represents values that never occur. This means that a variable declared as never can only be assigned to a value of type never, which in functions usually manifests as throwing an exception or failing to execute to a termination point (such as an infinite loop).

// A function that returns never can throw an exception
function error(message: string) :never {
    throw new Error(message);
}
// A function that returns a value of never may not be executed to a termination point
function loop() :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.

An API like object.create can be better represented by using the object type.

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

Type inference

Type inference helps provide types when initializing variables and members, setting default parameter values, and determining function return values.

let myFavoriteNumber = 'seven';
myFavoriteNumber = 7;
// index.ts(2,1): error TS2322: Type 'number' is not assignable to type 'string'.
Copy the code

If no value is assigned at the time of definition, whether or not a value is assigned later, it is inferred to be of type any without type checking at all.

let myFavoriteNumber;
myFavoriteNumber = 'seven';//true
myFavoriteNumber = 7;//true
Copy the code

The joint type

Union Types indicate that the value can be one of multiple Types. Joint type using | separated for each type.

let myFavoriteNumber: string | number;
myFavoriteNumber = 'seven';//true
myFavoriteNumber = 7;//true
Copy the code

When TypeScript does not determine what type a variable of a union type is, we can only access properties or methods that are common to all types of the union type.

Types of assertions

Type assertions can be used to specify the type of a value, allowing a variable to change from one type to another.

Syntax format

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

Or:

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

You must use the latter, the value as type, in TSX syntax (the TS version of React’s JSX syntax).

Syntax such as

represents a ReactNode in TSX, and may represent a generics in TS in addition to type assertions.

Purpose to summarize

  • The union type can be asserted as one of these types. (Type assertions are not cast, and assertions to a type that does not exist in the union type are not allowed. Type assertions can only “fool” the TypeScript compiler. They can’t avoid runtime errors, and abusing type assertions can lead to runtime errors.)
  • A parent class can be asserted as a subclass (used in practiceinstanceofMore appropriate)
class ApiError extends Error {
    code: number = 0;
}
class HttpError extends Error {
    statusCode: number = 200;
}

function isApiError(error: Error) {
    if (typeof (error as ApiError).code === 'number') {
        return true;
    }
    return false;
}
// The top and bottom are equivalent implementations
function isApiError(error: Error) {
    if (error instanceof ApiError) {
        return true;
    }
    return false;
}
Copy the code
  • Any type can be asserted as any. (Don’t abuse as any, but don’t negate it entirely. To get the best out of TypeScript, you need to strike a balance between typing rigor and ease of development, which is one of TypeScript’s design philosophies.)
  • Any can be asserted as any type