如何 return 基于通用输入类型输入?

How to return type based on generic input type?

我正在为 fetch 制作包装器。我想为所有 CRUD(post、获取、更新、删除)操作创建一个通用函数。 GET 请求 return 是一些数据,而 DELETE 请求可能 return 没有任何数据。

function fetchIt<T>(path: string, init?: RequestInit | undefined): T {
  // really use fetch
  // ...
  // if T is not provided return null
  //
  // if T is given return a value of type T

  return {} as T
}

interface User {
  name: string
}

// getResult should be of type User because we provided User as input type
const getResult = fetchIt<User>('/users/1')

// deleteResult should be null because we did not provide any input type
const deleteResult = fetchIt('/users')

这里是link到playground

我不想 return T | null 因为那样我总是要检查结果是否为空。

// this is not what I want
function fetchThis<T>(): T | null {
  return null
}

const a = fetchThis()
const b = fetchThis<User>()

if (b !== null) {
  console.log(b)
}

每当我不提供泛型类型时,我希望得到 null,而每当我提供类型时,它应该是 return 值。

有什么想法吗?非常感谢!

如果调用者未手动指定,您可能希望 T 本身为 null。如果是这样,您可以使用 generic parameter default= 语法:

function fetchIt<T = null>(path: string, init?: RequestInit | undefined): T {
  return {} as T; // unsafe assertion, but so is fetch() I guess so ‍♂️
}

这为您提供了您所要求的行为:

const getResult = fetchIt<User>('/users/1');
// const getResult: User
const deleteResult = fetchIt('/users');
// const deleteResult: null

Playground link to code