我有以下功能:
async function get<U>(url: string): Promise<U> {
return getUrl<u>(url);
}
Run Code Online (Sandbox Code Playgroud)
但是,可以像这样调用它(U由TS设置为任何):
get('/user-url');
Run Code Online (Sandbox Code Playgroud)
有没有办法定义这个函数,以便它需要显式提供U,如
get<User>('/user-url');
Run Code Online (Sandbox Code Playgroud) 如何使通用模板类型参数成为必需?
到目前为止,我发现这样做的唯一方法是使用never但它会导致错误发生在泛型调用点以外的其他地方。
此处粘贴的TypeScript Playground 示例:
type RequestType =
| 'foo'
| 'bar'
| 'baz'
interface SomeRequest {
id: string
type: RequestType
sessionId: string
bucket: string
params: Array<any>
}
type ResponseResult = string | number | boolean
async function sendWorkRequest<T extends ResponseResult = never>(
type: RequestType,
...params
): Promise<T> {
await this.readyDeferred.promise
const request: SomeRequest = {
id: 'abc',
bucket: 'bucket',
type,
sessionId: 'some session id',
params: [1,'two',3],
}
const p = new Promise<T>(() => {})
this.requests[request.id] …Run Code Online (Sandbox Code Playgroud)