泛型参数

function func<T>(value: T) {
    // ...
}

// 指定函数的参数为字符串类型
func<string>('123')

// 指定函数的参数为数字类型
func<number>(123)

泛型响应

function func<T>(): Promise<T>{
    // ...
}

// 指定函数的响应为字符串类型
func<string>()

// 指定函数的响应为数字类型
func<number>()

同时指定请求和响应为泛型

function func<T, U>(value: T): U {
  // ...
}

func<string, number>('123')

冗余应用应用场景

UserResponseNewsResponse属于冗余的定义。

interface User {
  id: string;
  name: string;
  age: number;
}

interface UserResponse {
  code: number;
  message: string;
  data: User[];
}

interface News {
  id: string;
  title: string;
  content: string;
}

interface NewsResponse {
  code: number;
  message: string;
  data: News[];
}

const getUserList = (url: string): Promise<UserResponse> => fetch(url).then(res => res.json())
const getNewsList = (url: string): Promise<NewsResponse> => fetch(url).then(res => res.json())

用泛型去掉UserResponseNewsResponse的冗余的定义。

interface User {
  id: string;
  name: string;
  age: number;
}

interface News {
  id: string;
  title: string;
  content: string;
}

interface ApiResponse<T> {
  code: number;
  message: string;
  data: T[];
}

const getUserList = (url: string): Promise<ApiResponse<User>> => fetch(url).then(res => res.json())
const getNewsList = (url: string): Promise<ApiResponse<News>> => fetch(url).then(res => res.json())

热饭班长
3.7k 声望434 粉丝

先去做,做出一坨狗屎,再改进。