【发布时间】:2018-11-01 21:50:06
【问题描述】:
如何使泛型模板类型参数成为必需?
到目前为止,我发现这样做的唯一方法是使用never,但这会导致错误发生在通用调用站点以外的其他位置。
TypeScript Playground example 贴在这里:
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] = p
this.worker.postMessage(request)
return p
}
// DOESN'T WORK
async function test1() {
const result = await sendWorkRequest('foo')
result.split('')
}
test1()
// WORKS
async function test2() {
const result = await sendWorkRequest<string>('foo')
result.split('')
}
test2()
正如您在对test1() 的调用中看到的,错误发生在result.split(''),因为never 没有.split() 方法。
在test2 中,当我提供通用 arg 时效果很好。
如果没有给出通用 arg,我怎样才能使 arg 成为必需,而不是使用 never,以及在调用 sendWorkRequest 时发生错误?
【问题讨论】:
标签: typescript generics