【发布时间】:2021-09-30 01:02:04
【问题描述】:
我正在为fetch 开发一个包装器。我想为所有 CRUD(发布、获取、更新、删除)操作创建一个通用函数。 GET 请求返回一些数据,而 DELETE 请求可能不会返回任何数据。
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')
这是playground的链接。
我不想返回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,而每当我提供类型时,它应该是返回值。
有什么想法吗?非常感谢!
【问题讨论】:
标签: typescript typescript-generics