打字稿:使用一个或另一个界面输入变量

时间:2019-09-11 22:53:32

标签: typescript

我一直在为此苦苦挣扎,看着StackOverflow,但不知道如何使它工作。

我想从一个API中键入response,如果成功,它可以返回一个接口,如果出错,则可以返回另一个接口。

我正在使用redux-saga

代码如下:

export interface IAuthSuccessResponse {
  token: string;
  email: string;
}

export interface IAuthErrorResponse {
  error: string;
}

type IAuthResponse = IAuthErrorResponse | IAuthSuccessResponse;

saga内:

    const response: IAuthResponse = yield call(Api.authenticate, tmpToken);
    const { error } = response // TS2339: property error doesnt exist on type IAuthResponse;

    if (error) {
      yield put(authenticateFailure(error));
    } else {
      const { token, email } = response // TS2339: property token/email doesnt exist on type IAuthResponse;

我收到此错误:TS2339: property error doesn't exist on type IAuthResponse

我想避免所有属性都是可选的。

正确的方法是什么?

1 个答案:

答案 0 :(得分:2)

您需要一个类型保护器来缩小类型。例如,您可以这样做:

if ("error" in response) {
    yield put(authenticateFailure(response.error));
} else {
    const {token, email} = response;
}

有关类型保护的更多信息,请参见《 TypeScript手册》的Type Guards and Differentiating Types部分。