This is the first day of my participation in the August Challenge. For details, see:August is more challenging

Literal assignment

interface IUserInfo {
  name: string.age: number
}

function printUserInfo(info: IUserInfo) {
  console.log(info.name)
}

// error ===> The type of the passed object is not the same as the type of the interface
printUserInfo({
  name: 'Klaus'.age: 23.address: 'shanghai'
})
Copy the code
interface IUserInfo {
  name: string.age: number
}

function printUserInfo(info: IUserInfo) {
  console.log(info.name)
}

const userInfo = {
  name: 'Klaus'.age: 23.address: 'shanghai'
}

// This is actually passing by reference
// In this case, ts performs type erasure, which removes redundant properties and methods
// If the removed type is the same as the required type, then ts considers the passed type to be error-free
// However, because of the type erasing, the passed object is not allowed to call the address property
printUserInfo(userInfo)
Copy the code

The enumeration

Enumeration is a list of possible values, one by one, defined in a type, this type is an enumeration type

One of the biggest benefits of enumerations is that they give readable names to some of the variables, improving the readability of the code

Enumerations allow developers to define a set of named constants. Constants can be of either number or string type

// Enumerations are constants, so they are all capitalized
// By default, enumerations are numeric enumerations, with values increasing from 0
// You can set the value manually.
// 1. The set value is a number. Before the enumeration value with the set value, the value continues to increase successively from 0
// 2. If the values are strings and cannot be increments, the value of each enumeration item must be set
enum Driection {
  UP,
  DOWN,
  LEFT,
  RIGHT
}
Copy the code

The generic

Generics are essentially type parameterization, that is, a generic is a type variable whose value is a type

// 
      
        -- define the type variable -- T is just the name of a variable. It can be any name, but it is generally uppercase
      
// param: T -- use type variables
function Foo<T> (param: T) {
  console.log(param)
}

// 
      
        -- assignment of type variables
      
Foo<number> (20)

// The assignment to the preceding type variable can be omitted, because TS does the type derivation automatically
Foo('Klaus')

// You can pass more than one parameter type
function Baz<K.V> (param1: K, param2: V) {
  console.log(param1, param2)
}
Copy the code
The variable name instructions
T Short for Type, Type
K, V Short for key and value, key-value pairs
E Short for Element, Element
O Short for Object, Object

A generic interface

// Generic interface
interface IUser<T, V> {
  name: T,
  age: V
}

const user1: IUser<string.number> = {
  name: 'Klaus'.age: 23
}

// When using a generic interface, we must manually specify the value of the generic type. The type derivation of TS does not accurately derive the value of the specific generic type
const user2: IUser = {
  name: 'Klaus'.age: 23
}
Copy the code

A generic class

/ / a generic class
class Point<T> {
  x: T
  y: T

  constructor(x: T, y: T) {
    this.x = x
    this.y = y
  }
}

// In this case, the generic value of the class can be derived using type inference
// Because the new class is essentially calling the constructor method of the class. The instance that initializes the class is essentially calling the method
const p1 = new Point(3.4)

// Manually specify a generic value
const p2 = new Point<number> (3.4)

// Manually specify a generic value in mode 2
const p3: Point<number> = new Point(3.4)
// Const arr: Array
      
        = [2, 3, 4]
      
Copy the code

Generic constraint

A generic constraint is a constraint on the value of the type passed in

interface ILength {
  length: number
}

function getLength<T extends ILength> (v: T) {
  return v.length
}
Copy the code

The namespace

TypeScript supports two ways to control our scope

  1. Namespaces: Declare a namespace through a namespace (ts implemented modularized way before THE ESM was introduced, not commonly used now)
  2. Modularity: Each file can be a separate Module, supporting ES Modules as well as CommonJS

In the early days of TypeScript, namespaces were called internal modules. The main purpose of namespaces was to re-scope a module to prevent naming conflicts

// Each command space is a separate module within a module
namespace foo {
  let name = 'foo'

  // Export is required for external use
  export function printName() {
    console.log(name)
  }
}

// Export the namespace if you want files outside the module to use the properties and methods exposed in the namespace
export namespace baz {
  let name = 'baz'

  export function printName() {
    console.log(name)
  }
}

// Call the corresponding method in the namespace
foo.printName()
baz.printName()
Copy the code

Type of lookup

Type declaration file

The main effect of TS on JS is to add type constraints, but sometimes we want to introduce JS files into TS,

The js file itself does not have type constraints, and when introduced directly, errors will be reported, so you can add type declaration files

There are two types of file suffixes in TS:.ts and.d.ts

.ts files, which eventually output.js files, where we usually write code

The.d.ts file is used to declare types. It’s just used for type checking, telling typescript what types we have, and it’s not compiled to js files

Type lookup classification

  • Built-in type declarations – type declarations that are downloaded after the ts package is downloaded. They are stored in the typescript/lib folder and are used to define common ES objects and methods, such as window, document, The specific declaration file can be viewed in the typescript project

  • External defined type declarations – External type declarations are usually required when we use libraries such as third-party libraries

    There are two ways to declare an external type:

    • Type declarations (writing.d.ts files) in your own library, such as Axios

      // The AXIos library comes with its own declaration file, so you can use it directly after importing it
      import axios from 'axios'
      Copy the code
    • Store type declarations through DefinitelyTyped, a public library in the community

      // Loadsh has no built-in type declaration file, but it is defined in the DefinitelyTyped community project
      // At this point, after installing the lodash type declaration file, you can use loadsh in ts
      // npm i loadsh -S
      // npm i @types/loadsh -D
      import _ from 'lodash'
      
      // We can see which modules have third-party type declaration files in the url below
      // https://www.typescriptlang.org/dt/search?search= 
      Copy the code
  • Define your own type declaration

  1. The third-party library we use is a pure JavaScript library with no corresponding third-party declaration file
  2. We declare some types in our code so that we can use them directly elsewhere

The. D. ts file can be defined anywhere in the project, but it is recommended to place it under the types folder

index.d.ts

// the d.ts file only completes the type declaration and does not implement the corresponding logic

// Declare variables
declare const user: { name: string }

// Declare the function
declare function printInfo(user: {name: string}) :void/ / class declarationdeclare class Person {
  name: string
  age: number
  constructor(name:string, age: number} // Declare the moduledeclare module 'lodash'{// Define the method to call
  export function join(arr: any[]) :void} // Declare the filedeclare module '*.jpg// Declare the namespacedeclare namespace $ {
  export function ajax(settings: any) :any
}
Copy the code