相关疑难解决方法(0)

TypeScript需要提供通用参数

我有以下功能:

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)

javascript typescript

11
推荐指数
3
解决办法
856
查看次数

如何在打字稿中使用泛型类型参数?

如何使通用模板类型参数成为必需?

到目前为止,我发现这样做的唯一方法是使用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)

generics typescript

7
推荐指数
2
解决办法
5678
查看次数

标签 统计

typescript ×2

generics ×1

javascript ×1