如何创建 `TResponse | 的返回类型TError`?

问题描述 投票:0回答:1

我正在尝试找到一种返回类型为

TData | TError
的方法。
这就是我尝试过的(TS Playground):

type MyResponse = {
  data: any;
}

type UIError<TError = unknown> = {
  error: TError;
}

abstract class BaseClass {
  public abstract userAuth<
    TResponse extends MyResponse = MyResponse,
    TError extends UIError = UIError
  >(): Promise<TResponse | TError>;
}

class TestClass extends BaseClass {
  public userAuth<
    TResponse extends MyResponse = MyResponse,
    TError extends UIError = UIError<any>>(): Promise<TResponse | TError> {
    throw new Error("Method not implemented.");
  }
}

但是在

TestClass
我不断得到:

Type 'MyResponse | UIError<unknown>' is not assignable to type 'TResponse | TError'

关于如何修复它有什么想法吗?
谢谢

typescript generics types
1个回答
0
投票

将参数设为泛型参数对你有用吗?

所以像这样:

abstract class BaseClass {
  public abstract userAuth<
    TResponse extends MyResponse = MyResponse,
    TError extends unknown = unknown
  >(): TResponse | UIError<TError>;
}

class TestClass extends BaseClass {
  public userAuth<
    TResponse extends MyResponse = MyResponse, TError extends unknown = unknown>(): TResponse | UIError<TError> {
      throw new Error("Method not implemented.")
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.