This is the third day of my participation in the August Text Challenge.More challenges in August

The installation

#After installing typescript, there is a directive TSC (typescript Compiler) to help convert TS to JS
#Global installation is intended to make TSC a global command line directive that can be installed and used locally based on project requirements
npm install typescript -g
Copy the code

use

TypeScript can be used through the command line tool TSC or by integrating TS compilation into the build tool using plug-ins such as ts-Loader in WebPack

#After compiling, a JS file with the same name as the source file is generated in the same directory as the source fileTSC < source file name or folder name >
#Only type verification is performed, but compiled JS files are not generatedTSC < source filename or folder name > --noEmit
#Real-time compile monitorTSC < source filename or folder name > --watchCopy the code

Type annotation

At its core, TypeScript adds a type system to JavaScript

TypeScript detects our data types in the form of type annotations

So TypeScript type detection is static and performed at compile time

// Type: type annotation = value
let ts: string = 'typeScript'
Copy the code

Note: Type annotations are case sensitive, and number and number are not a data type

// baz is a string
let baz: string = 'typeScript'

// bar is the string wrapper class type
let bar: String = 'typeScript'
Copy the code

The data type

The most basic processing unit of a program is data types: numbers, strings, structures, booleans, etc

TypeScript supports almost the same data types as JavaScript and extends them accordingly

boolean

As in JavaScript, Boolean types in TypeScript have only true/false values

let isDone: boolean = false;
Copy the code

number

Like JavaScript, all numbers in TypeScript are floating point (number) or bigInt.

Number in TypeScript supports decimal, octal, binary, and hexadecimal numbers

// Base identifiers are case insensitive 0B1010 <=> 0B1010, 0xf00D <=> 0xf00D,...
let decLiteral: number = 6; / / decimal
let hexLiteral: number = 0xf00d; // Hexadecimal
let binaryLiteral: number = 0b1010; / / binary
let octalLiteral: number = 0o744; / / octal

// bigInt n is case sensitive
// bigInt is of type bigInt ==> all lowercase
let bigLiteral: bigint = 100n;
let foo: bigint = 100N; // => error
Copy the code

string

Like JavaScript, you can use double quotes (“) or single quotes (‘) and template strings to represent strings.

let firstname: string = 'Klaus'
let lastname: string = 'Wang'
let fullname: string = `${firstname} - ${lastname}`
Copy the code

array

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

tuple

A tuple type allows you to represent an array with a known number and type of elements. The elements need not be of the same type. You can think of a tuple as a special type of array

Tuples have the following two characteristics:

  1. The length of a tuple is fixed
  2. The data type of the data item at each position in the tuple is determined (it may not be the same)
// Declare a tuple type
let x: [string.number];

// Initialize it
x = ['hello'.10]; // OK

// Initialize it incorrectly
x = [10.'hello']; // Error

// When accessing an element with a known index, the correct type is obtained
console.log(x[0].substr(1));

// An error is reported when accessing an out-of-bounds element.
x[3] = "world";
console.log(x[5].toString());
Copy the code

enum

Enum types complement the JavaScript standard data types.

The main use of enumerated types is to give friendly names to a set of values.

enum Color {Red, Green, Blue}

// By default, elements are numbered from 0.
let c: Color = Color.Green; // equivalent to let c = 1
Copy the code
// You can manually specify the value of the member
// The assigned value must be a string or numeric type
enum Color {Red, Green = 2, Blue} // { Red: 0, Green: 2, Blue: 3 }

// Alternatively, all manual assignments are used
enum Color {Red = 1, Green = 2, Blue = 4}
Copy the code
// You can get an alias from an enumeration value or an alias from an enumeration value
enum Color {Red = 1, Green, Blue}

console.log(Color.Green) / / = > 2
console.log(Color[2]) // => 'Green'
Copy the code

any

  1. The data type of the variable is not known at the programming stage
  2. You don’t want the type checker to check these values but to pass them directly through compile-time checks
// any => No type detection, which is equivalent to a placeholder
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; 
Copy the code

The any type is useful when rewriting existing code, allowing you to optionally include or remove type checking at compile time.

// As in other languages, object has a similar function to any, but there are essential differences

let notSure: any = 4;
// Set any to skip type detection, so any method can be called, whether it exists or not
notSure.ifItExists(); // success
notSure.toFixed(); // success

let prettySure: Object = 4;
// Set object, which typescript recognizes as the top-level object type object
// This variable can only call methods that are common to all objects, that is, methods defined in the Object prototype
// None of the other methods can be called, even if it does have them
prettySure.toString(); // success
prettySure.toFixed(); // error
Copy the code

Note:

  1. Avoid usingobjectInstead, use non-originalobjecttype
  2. Avoid usinganyInstead, useunknowntype

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

unknown

  1. The data type of the variable is not known at the programming stage
  2. You want to let the compiler and future users know that this variable can be of any type
  3. You do not want this variable to bypass the type detector
let notSure: unknown = 4;
notSure = "maybe a string instead";
notSure = false;
Copy the code

In this way, unknown and any seem to be the same, but they have this essential difference

let any: any
let unknown: unknown

let num: number
let str: string

// Any is both the top-level type and the lowest type - any is anything without type restriction
// Any can be assigned to any data type
num = any
str = any

// Unknown is the topmost type, but not the lowest type -- unknown is not certain, but does not want to have no type detection
// Unknown cannot be assigned to any data type
num = unknown // error
str = unknown // error

// Unknown and any are both top-level types and can be assigned to each other
unknown = any // success
any = unknown // success => unknown Can only be assigned to values of unknown type and values of any type
Copy the code

If you have a variable of type Unknwon, you can narrow it down by typeof, comparison, or more advanced type checking,

Casts unknown to a more concrete type

const maybe: unknown;

if (maybe === true) { // Maybe has been reduced from unknown to Boolan
  const aBoolean: boolean = maybe; // success
  const aString: string = maybe; // error
}

if (typeof maybe === "string") { // Maybe is reduced from unknown to string
  const aString: string = maybe; // success
  const aBoolean: boolean = maybe; // error
}
Copy the code

Null, and undefined

  1. Undefined and NULL have their own types called undefined and NULL, respectively

  2. Like void, their own type is not very useful

  3. By default null and undefined are subtypes of all types.

    That is, you can assign null and undefined to any other value of any type

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

Note: in real development, it is recommended to turn on the –strictNullChecks’ flag as much as possible

When strictNullChecks is specified, null and undefined can only be assigned to any and their respective types. This can avoid many of the common problems (except that undefined can be assigned to void types).

Maybe somewhere you want to pass in a string or null or undefined, you can use the combined type string | null | is undefined.

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 will usually see the return type void

// In JavaScript, when a function returns no value, the return value is undefined,
// Therefore, in typescript, undefined is a subtype of void
function warnUser() :void {
  console.log("This is my warning message");
}
Copy the code

It is possible to declare a variable of type void, but this is usually of little use because you can only give it null (only if –strictNullChecks is not specified) and undefined

let unusable: void = undefined;
Copy the code

never

  1. neverA type represents the type of a value that never exists
  2. neverTypes are the return value types of function expressions or arrow function expressions that always throw an exception or have no return value at all
  3. neverA type is a subtype of any type and can be assigned to any type;
  4. No type isneverCan be assigned to a subtype ofneverType (exceptneverOutside of itself)
  5. Even if theanyIt cannot be assigned tonever
// A function that returns never must have an unreachable end
function error(message: string) :never {
    throw new Error(message);
}

// 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, Bigint, symbol, NULL, or undefined

In most cases, we recommend defining objects in a more concrete form, such as an interface, because this allows us to more accurately determine the data types of the various attributes in the object

// Define more specific types directly
let user: {
  name: string.age: number
}

// Or use interfaces
interface IUser {
  name: string.age: number
}

let user: IUser
Copy the code

However, when we only use objects as parameters, we do not care about the type of the Object’s attribute value (for example, when defining methods such as object.create).

We can use object as a type annotation

declare function create(o: object | null) :void;

create({ prop: 0 }); // success
create(null); // success

create(42); // error
create("string"); // error
Copy the code

Types of assertions

Sometimes we know more about the details of a value than TypeScript does, and we know that an entity has a more exact type than it already has.

Type assertion is like casting in other languages, except that type assertion has no run-time impact and only takes effect at compile time.

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. In practice, however, it is recommended to use AS for type assertion. Because when you use JSX in TypeScript, only AS syntax assertions are allowed.

function getLength(param: number | string) {
 return param.length ? param.length : param.toString().length // error
}
Copy the code

At this point, however, we know that we’re writing a function that doesn’t have any problems, so to address the TypeScript type detector error,

At this point we can use type assertion (currently we can also use type guard to solve this problem, using type assertion as an example)

function getLength(param: number | string) {
 return (param as string).length ? (param as string).length : param.toString().length
}
Copy the code

Typically, the TypeSCript compiler assumes that type assertions can only be used between two types that are related; otherwise, type assertions fail

const num: number = 123
const str: string = num as string // Error type assertion failed
Copy the code

If you do need to cast, you can first cast the data type to any or unknown, and then cast it to a specific type

This is not recommended unless you absolutely have to

const num: number = 123
const str: string = num as unknown as string // success
Copy the code