The use of typescript in the business is more focused on business development itself. For example: user login, data list, detail page, security information, analysis chart, according to the data type abstracted out, we try to write together. Assuming you’re already familiar with type arithmetic, if not, read a typescript article to learn more about the underlying dynamics of type arithmetic. Let’s get started…
The original type
const isLogin: boolean = false;
const price: number = 1;
const userName: string = "Lucy";
// Unique identifier
const unique: symbol = Symbol("unique");
Copy the code
Object type
LoginReqByAccount or LoginReqParamsByOther */
type LoginType = "account" | "other";
// Account login request parameters
interface LoginReqByAccount {
name: string;
password: string;
phone: number;
// Login type
type: LoginType; keepPwd? :boolean;
}
// Request parameters for other login methods
interface LoginReqParamsByOther {
id: number;
/ / signature
sign: string;
// Login type
type: LoginType;
}
// Request parameters for login
type LoginParams = LoginReqByAccount | LoginReqParamsByOther;
// Service data returned in the background
type ResBusinessData = {
userId: number;
/ / user name
name: string;
// Nickname, optionalnickName? :string;
// Membership level
level: number;
// Other attributes
[p: string]: unknown;
} | null;
interface LoginResponse {
code: number;
// Description of the success error message
message: string;
// Business data
data: ResBusinessData;
}
/ / paging
interface Pagination<T extends number = number> {
current: T;
pageSize: T;
}
// Define a map of states to represent different state ICONS
const StatusMap: Map<number.string> = new Map([[0."info"],
[1."success"],
[2."warning"],
[3."error"]]);interface PrivilegeShape<T extends number | boolean> {
[P: string]: T;
}
// Member privileges
const MemberPrivilege: PrivilegeShape<boolean> = {
/ / discount
discount: true./ / free shipping
freeShipping: false};Copy the code
List the type
// List item 1
interface ListItem1 {
id: number;
/ / title
title: string;
/ / price
price: number;
/ / promotion
promotion: boolean;
/ / inventory
stock: number;
/ / description
desc: string;
}
// List item 2
interface ListItem2 {
id: number;
/ / title
title: string;
desc: string;
// Other attributes
others: {
children: number[];
};
}
/ / list
let list: (ListItem1 | ListItem2)[] = [];
/ / collection
const productionIds: Set<number> = new Set([1.2.3.4]);
const userNames: Set<string> = new Set(["a"."b"."c"]);
Copy the code
The tree
interface TreeData {
id: number;
parentId: number | null; groupId? :number;
name: string;
phone: number;
}
type Tree<T extends TreeData> = {
id: number;
level: number; data: T; children? : Tree<T>[]; };Copy the code
Third-party libraries
Declaration documents can be divided into two types in terms of source:
-
One option is to write your own files that can be stored locally and, of course, published as packages to the typescript declaration file library.
-
There’s also a third-party library declaration file, the typescript declaration file platform, that searches for declarations to install,
Some packages come with the installation declaration file when you install, which is relatively sweet. For example, axios is installed in node_modules/axios/index.d.ts. Some should be installed separately, such as Express.
// Run the NPN I axios or yarn add axios command
// Using axios as an example, import the required type directly
import axios, { AxiosRequestConfig } from "axios";
// Request interceptor
const reqInterceptor = (config: AxiosRequestConfig): AxiosRequestConfig= > {
// Do some intercepting
return config;
};
axios.interceptors.request.use(reqInterceptor);
Copy the code
Function types
// Get the list of data
function fetchList<T> (params: { id: number; name: string } & Pagination) {
return axios.post<{ total: number; data: T[] }>("/list", params);
}
fetchList<{ id: number; [p: string]: unknown }>({
id: 0.name: "".current: 1.pageSize: 10});type TreeNode = {
id: number;
name: string; children? : TreeNode[]; };/ * * * *@param List array node *@param TargetId Indicates the ID *@param Stack chases location information */
function getArrayIndex(
list: TreeNode[],
targetId: number,
stack: number[] = []
) :number[] {
list.some((item, idx) = > {
stack.push(idx);
const found = item.id === targetId;
if(! found) {const { children = [] } = item;
if (children.length > 0) {
const len = stack.length;
getArrayIndex(children, targetId, stack);
return stack.length > len ? true : (stack.pop(), false);
} else{ stack.pop(); }}return found;
});
return stack;
}
Copy the code
conclusion
Each program is processing data, abstracted into a data type declaration, you can draw inferences, try to write a write. Writing a declaration file is typescipt’s way of completely focusing on types without any business in it. So why don’t we give it a try?
If there are any mistakes or omissions in this article, please correct them. Thank you.