在typescript中合并接口内的对象

时间:2018-01-05 12:57:35

标签: typescript typescript-typings

我在打字文件中有以下内容:

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.http.Cookies;

private Cookie cookie;

@BeforeClass
public void exampleOfLogin() {
    String body = String.format("//json");
    cookies = RestAssured.given()
            .contentType(ContentType.JSON)
            .when()
            .body(body)
            .post("www.test_test.com")
            .then()
            .statusCode(200)
            .extract()
            .response()
            .getDetailedCookies();
}

@Test
public void performActionsBasedOnCookies() {
//set cookies before making a post request and check the returned status code
    RestAssured.given()
            .cookies(cookies)
            .contentType(ContentType.JSON)
            .when()
            .post("www.test_url.com")
            .then()
            .statusCode(200);
}

现在我想更改界面,以便 anObject 还包含 data2 。我希望最后的表格是

interface A {
    anObject: {
        data: string;
    };
    someOtherData: boolean;
}

我已经尝试过这样做但失败了:

interface A {
    anObject: {
        data: string;
        data2: string;
    };
    someOtherData: boolean;
}

而不是具有data和data2的 anObject ,它只有data2。无论如何要保留原始密钥吗?

1 个答案:

答案 0 :(得分:4)

嗯,这样的事情怎么样:

orig.ts

export interface A {
    anObject: {
        data: string;
    };
    someOtherData: boolean;
}

extend.ts

import {A as _A} from './orig'

interface A extends _A {
  anObject: _A['anObject'] & {
    data2: string;
  }
}

即:在import期间将原始A重命名为_A。然后对其进行扩展,并将新data2属性与intersecting原始looked-up属性合并到{{3}} anObject属性中。

或者,如果您不介意Atype别名而不是interface,那么更简单:

extend.ts

import {A as _A} from './playground'

type A = _A & {
  anObject: {
    data2: string;
  }
}

...您仍然将原始文件重命名,但之后只需将其与新部分相交。这两种方法都可以为您提供所需的类型:

declare const a: A;
a.anObject.data.charAt(0); // okay
a.anObject.data2.charAt(0); // okay

这有帮助吗?