A special data type in TypeScript

The data type role
any It allows you to optionally include or remove type checking at compile time.
unknown Type safe any
void Null value (undefined)
never It can’t be any value
tuple The tuple type allows you to represent an array with a known number and type of elements that need not be of the same type
enum Enumeration, TS new type

Difference between any and unknown

/ / any use
let a: any = 'hello';
a = 123 // It has the same properties as js
let b: number;
b = a; // Type checking is removed during assignment, and type checking is lost for b
console.log(b); 
/ / the use of the unknown
let a: unknown = 'hello';
a = 123
let b: number;
b = a; // Error - cannot assign type "unknown" to type "number"
Copy the code

Using unknown ensures type-safety, while using any eliminates type-checking altogether. In many cases, we can use unknow instead of any to be flexible and still be type-safe.

The difference between any and unknown is that unknown is the top type. Any is the top type. Bottom type again (which is a subtype of any type), which results in any basically abandoning any type checking.

Unknown is assigned

// Use an assertion to use unknown assignment
// Method 1: Angle brackets
let a: unknown = 'hello';
a = 123
let b: number;
b = <number>a;/ / is not an error
// Method 2: as
let a: unknown = 'hello';
a = 123
let b: number;
b = a as number;/ / is not an error

// Evaluate before assigning
let a: unknown = 'hello';
a = 123
let b: number;
if(typeof a === 'number'){
  b = a / / is not an error
}
console.log(b);
Copy the code

Object methods are commonly declared in TypeScript

// Name is mandatory and age is optional
let person: {
  name:string, age? :number / /? Append the attribute name with? , indicating that the property is optional
};
person = {
  name:'little red'.age:13
}
// Name is mandatory, other optional
let person: {name:stirng,[propName:string] :any};
person = {name: 'Ming'.age: 19.gender:'male'}
Copy the code

Difference between void and never

//void
function warnUser() :void {
    console.log("This is my warning message");
}
// For variables declared as void, only undefined and null can be assigned
let unusable: void = undefined;
//never
// A function that returns never must have an unreachable end
// Because exceptions are always thrown, error will not return a value
function error(message: string) :never {
    throw new Error(message);
}
// infiniteLoop will have no return value because of an infiniteLoop
function infiniteLoop() :never {
    while (true) {}}Copy the code

Void denotes no type, and never denotes the type of a value that never exists. Null and undefined are subtypes of void. Never is a subtype of all types, so it can be interpreted as: all functions return values that contain never:

function fun(s: string) :number {
  if (s == 'a') return 1;
  if (s == 'b') return 2;
  throw new Error;
}
/ / equal fun (s: string) : number | never
Copy the code

Array methods are often declared in TypeScript

  1. Type []
  2. Array < type >
// Declare an array of single data types
let a: string[];
let c: Array<string>;
a = ['a'.'b'.'c'];
let b: number[];
let d: Array<number>;
b = [1.2.3];
// An array of any data type
let e: Array<any>;
let f: Array<unknown>;
Copy the code

Enum enumeration

One of the conveniences provided by an enumerated type is that you can refer to its name by enumeration. For example, if we know that the value is 2, but are not sure which name in Color it maps to, we can look for the corresponding name:

enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];

console.log(colorName);  // Display 'Green' because its value is 2 in the code above
Copy the code

Null and undefined are subtypes of other types, including void, and can be assigned to other types

Null and undefined are subtypes of other types, including void, and can be assigned to other types

let a:number;
a = undefined;
Copy the code

By default, the compiler prompts an error because tsconfig.json has a configuration item that is enabled by default.

// tsconfig.json 

{
 	 /* Strict Type-Checking Options */
    "strict": true./* Enable all strict type-checking options. */
    // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
    // Check for null types. If set to false, no errors are reported
    // "strictNullChecks": true, /* Enable strict null checks. */
    // "strictFunctionTypes": true, /* Enable strict checking of function types. */
    // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
}
Copy the code

StrictNullChecks the strictNullChecks parameter is used in the new strictNullChecks mode. In strictNullChecks mode, null and undefined are not of either type. They can only be assigned to their own type or to any

Yuan Zu trespassing problem

let aaa: [string.number] = ['aaa'.5];
// No error will be reported when adding
aaa.push(6);
// Print the entire ancestor without error
console.log(aaa); / / [' aaa ', 5, 6].
// An error occurs when printing added elements
console.log(aaa[2]); // error
Copy the code

Tsconfig. json Configuration information

1. The exclude exclude attribute specifies files or folders that the compiler should exclude.

{
	// ...
  "exclude": [
    "src/lib" // do not compile files in lib folder under SRC directory]}Copy the code

2. The extends extends property extends the configuration by importing other configuration files.

{
	// ...
  // Extract the base configuration into the tsconfig.base.json file and import it
	"extends": "./tsconfig.base.json"
}
Copy the code

3. Files The Files property specifies a list of individual files to be compiled.

{
	// ...
  "files": [
    // Specify that the compiled file is leo.ts in the SRC directory
    "scr/leo.ts"]}Copy the code

The include include attribute specifies the files or directories to be compiled.

{
	// ...
  "include": [
    // "SCR" // will compile all files under SRC, including subdirectories
    // "SCR /*" // only files in SCR level 1 directories will be compiled
    "scr/*/*" // Only files in SCR level 2 will be compiled]}Copy the code

5. CompileOnSave The compileOnSave property allows you to automatically compile files when you save them.

{
  "compileOnSave": false,}Copy the code

6. CompilerOptions The compilerOptions property configures compilation options.

{
  // ...
  "compilerOptions": {
    "incremental": true.// The TS compiler generates a file to store the compilation information after the first compilation. The second compilation will be incremental on the basis of the first compilation, which can improve the compilation speed
    "tsBuildInfoFile": "./buildFile".// Where the incremental compiled file is stored
    "diagnostics": true.// Prints diagnostic information
    "target": "ES5".// The target language version
    "module": "CommonJS".// A template standard for generating code
    "outFile": "./app.js".// Generate a file from multiple interdependent files, which can be used in AMD modules, i.e. "module": "AMD",
    "lib": ["DOM"."ES2015"."ScriptHost"."ES2019.Array"].By default, ES5 references DOM, ES5, scripthost. If you need to use the advanced version features of ES, they usually need to be configured. For example, the new Array features of ES8 need to introduce "ES209.array".
    "allowJS": true.// Allows the compiler to compile JS, JSX files
    "checkJs": true.// Allows errors to be reported in JS files, usually with allowJS
    "outDir": "./dist".// Specify the output directory
    "rootDir": ". /".// Specify the output file directory (for output), which controls the output directory structure
    "declaration": true.// Generate a declaration file. After this function is enabled, the declaration file will be generated automatically
    "declarationDir": "./file".// Specify the directory to store the build declaration file
    "emitDeclarationOnly": true.// Only declaration files are generated, not js files
    "sourceMap": true.// Generate the sourceMap file for the target file
    "inlineSourceMap": true.// Generate an inline SourceMap for the target file, which is included in the generated JS file
    "declarationMap": true.// Generate sourceMap for the declaration file
    "typeRoots": [].// Declare the file directory, default node_modules/@types
    "types": [].// Load the declaration file package
    "removeComments":true.// Delete comments
    "noEmit": true.// No output file, that is, no JS files are generated after compilation
    "noEmitOnError": true.// No files are output when errors are sent
    "noEmitHelpers": true.// Do not generate helper functions, reduce the volume, requires additional installation, often used with importHelpers
    "importHelpers": true.// Introduce helper functions via tslib. The file must be a module
    "downlevelIteration": true.// Degraded traverser implementation, if the target source is ES3/5, then traverser will have degraded implementation
    "strict": true.// Turn on all strict type checking
    "alwaysStrict": true.// Inject 'use strict' into the code
    "noImplicitAny": true.// Implicit any types are not allowed
    "strictNullChecks": true.// It is not allowed to assign null and undefined to variables of other types
    "strictFunctionTypes": true.// Bidirectional covariance of function arguments is not allowed
    "strictPropertyInitialization": true.Class instance attributes must be initialized
    "strictBindCallApply": true.// Strict bind/call/apply check
    "noImplicitThis": true.This is not allowed to have an implicit any type
    "noUnusedLocals": true.// Check for declared, unused local variables
    "noUnusedParameters": true.// Check for unused function arguments.
    "noFallthroughCasesInSwitch": true.// Prevent switch statements from running through (i.e., if there is no break statement, it will not be executed)
    "noImplicitReturns": true.// Each branch returns a value
    "esModuleInterop": true.// Allow export= export, import from import
    "allowUmdGlobalAccess": true.// Allow access to the UMD module as a global variable within the module
    "moduleResolution": "node".// Module parsing policy. Ts uses node parsing policy by default, that is, relative import
    "baseUrl": ". /".// Resolve the base address of a non-relative module, default is the current directory
    "paths": { // Path mapping, relative to baseUrl
      // If you do not want to use the default jQ version and need to manually specify the version, perform the following operations
      "jquery": ["node_modules/jquery/dist/jquery.min.js"]},"rootDirs": ["src"."out"].SRC and out can be placed in the same directory without changing the path and will not report errors
    "listEmittedFiles": true.// Print the output file
    "listFiles": true// Print the compiled file (including the referenced declaration file)}}Copy the code

class

readonlyThe modifier

You can use the readonly keyword to make the property read-only. Read-only attributes must be initialized at declaration time or in a constructor.

class Octopus {
    readonly name: string;
    readonly numberOfLegs: number = 8;
    constructor (theName: string) {
        this.name = theName; }}let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; / / error! Name is read-only.
Copy the code

Static attributesstatic

class Person{
  static people:string = 'hello';
  age:number;
  constructor(age:number){
    this.age = age; }}let man = new Person(14);
console.log(man.people);Static properties cannot be accessed through the instance object
console.log(Person.people);//'hello'
Copy the code

privatePrivate property

When a member is marked private, it cannot be accessed outside the class in which it is declared. Such as:

class Animal {
    private name: string;
    constructor(theName: string) { this.name = theName; }}new Animal("Cat").name; // Error: 'name' is private.
Copy the code

understandprotected

Protected modifiers behave much like private modifiers, with one difference: protected members are still accessible in derived classes.

class Person {
    protected name: string;
    constructor(name: string) { this.name = name; }}class Employee extends Person {
    private department: string;

    constructor(name: string, department: string) {
        super(name)
        this.department = department;
    }

    public getElevatorPitch() {
        return `Hello, my name is The ${this.name} and I work in The ${this.department}. `; }}let howard = new Employee("Howard"."Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); / / error
Copy the code

interface

Interfaces are used to name these types and define contracts for your code or third-party code. None of the attributes in the interface can have actual values. An interface defines only the structure of an object, regardless of its actual value.

interface myType{
  name:string;
  age:number;
}
const obj:myType = {
  name:'hello';
  age:17;
}

interface myInter{
  name:string;
  age:number;
}
class MyClass implements myInter{
  // Can be automatically implemented interface
  name:string;
  age:number;
}
Copy the code

Function type interface

// Common interface
interface discount1{
  getNum : (price:number) = > number
}
// Function type interface
interface discount2{
  / / note:
  // The signature before the ":" is used to constrain the parameters of the function
  // ":" is used to constrain the return value of the function
  (price:number) :number
}
let cost:discount2 = function(price:number) :number{
   return price * 8.;
}
Copy the code

Mixed-type interface

An object can be used as both a function and an object

interface FnType {
    (getName:string) :string;
}

interface MixedType extends FnType{
    name:string;
    age:number;
}
Copy the code
interface Counter {
    (start: number) :string;
    interval: number;
    reset(): void;
}

function getCounter() :Counter {
    let counter = <Counter>function (start: number) {}; counter.interval =123;
    counter.reset = function () {};return counter;
}

let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;
Copy the code

The generic

A generic type is a feature that does not specify a specific type when defining a function, interface, or class. When defining functions or classes, you can use generics if the type is unclear.


       
       
      
function createArray<T> (length: number, value: T) :Array<T> {
    let result: T[] = [];
    for (let i = 0; i < length; i++) {
        result[i] = value;
    }
    return result;
}
// Specify the type when used
let result = createArray<string> (3.'x');

// You can also specify no type, TS will automatically derive the type
let result2 = createArray(3.'x');
console.log(result);
Copy the code