[英]How to infer the return type of a generic function based on its input type?
[英]How to return type based on generic input type?
我正在研究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')
这是游乐场的链接。
我不想回T | null
T | null
因为那样我总是要检查结果是否为 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
,每当我提供类型时,它都应该是返回值。
有任何想法吗? 非常感谢你!
当调用者未手动指定T
时,您可能希望T
本身为null
。 如果是这样,您可以使用带有=
语法的通用参数默认值:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.