如何断言受歧视的联合在打字稿单元测试中具有某种变体?

fz_*_*lam 5 unit-testing typescript jestjs

我试图使用笑话在打字稿中编写单元测试。

// This is how foo() is defined:
// function foo(): 
//        {status: "OK"} | 
          {status: "ERROR", reason: "INVALID_ID"|"SOME_OTHER_ERROR"};

let res = foo();
expect(res.status).toEqual("ERROR");
expect(res.reason).toEqual("INVALID_ID");
// ^^^ this line gives error TS2339: Property 'reason' does not exist on type ....
Run Code Online (Sandbox Code Playgroud)

打字稿是否具有某种构造,assert(res.status == "ERROR")例如编译器可以在其中找出结果是这里的第二个变体?

如果没有,是否有其他单元测试框架在其expect()类似功能中向编译器提供必要的提示?

或者有更好的方法来返回错误foo()吗?

Mat*_*ocz 4

在您的情况下,您可以只使用简单的类型断言。

// Store the type for convenience.
type ErrorResponse = {status: "ERROR", reason: "INVALID_ID"|"SOME_OTHER_ERROR"}


let res = foo();
expect((res as ErrorResponse).reason).toEqual("INVALID_ID");
Run Code Online (Sandbox Code Playgroud)

在更高级的场景中,您可能需要使用类型保护

type OkResponse = {status: "OK"}
type ErrorResponse = {status: "ERROR", reason: "INVALID_ID"|"SOME_OTHER_ERROR"};

function isErrorResponse(response: OkResponse | ErrorResponse): response is ErrorResponse {
  return response.status === "ERROR"
}

Run Code Online (Sandbox Code Playgroud)