如何根据通用输入类型返回类型?

时间:2021-07-22 18:45:41

标签: typescript typescript-generics

我正在研究 function getPair(token0, token1) { const hexadem = '0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'; const factory = '0xBCfCcbde45cE874adCB698cC183deBcF17952812'; let salt = web3.utils.soliditySha3(token0, token1); let pair = web3.utils.soliditySha3('0xff', factory, salt, hexadem); console.log(pair); return pair } 的包装器。我想为所有 CRUD(发布、获取、更新、删除)操作创建一个通用函数。 GET 请求会返回一些数据,而 DELETE 请求可能不会返回任何数据。

fetch

这是 playground 的链接。

我不想返回 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

每当我不提供泛型类型并且提供类型时,它都应该是返回值。

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

1 个答案:

答案 0 :(得分:3)

当调用者未手动指定时,您可能希望 T 本身为 null。如果是这样,您可以使用带有 = 语法的 AWS does not allow you to combine "Action" and "NotAction" fields in the same policy statement.

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

generic parameter default