相关疑难解决方法(0)

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

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

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

如何使类的泛型是必需的?

班级是:

class Test<P> {
  constructor(data: P) {}
}
Run Code Online (Sandbox Code Playgroud)

我希望下面的代码没有通过类型检查,因为它没有传入的泛型:

new Test({ a: 1 })
Run Code Online (Sandbox Code Playgroud)

我知道上面的泛型 P 是自动派生为 的{a: number},但这不是我想要的,下面是。

new Test< {a: number} >({ a: 1 })
Run Code Online (Sandbox Code Playgroud)

我尝试了很多方法,但最终泛型 P 会自动派生到构造函数的参数类型中。

typescript

5
推荐指数
2
解决办法
716
查看次数

标签 统计

typescript ×2

generics ×1