gpt4 book ai didi

typescript - 如何在 beforeAll 测试中创建类型变量?

转载 作者:搜寻专家 更新时间:2023-10-30 21:01:46 29 4
gpt4 key购买 nike

我遇到了一个常见的场景。我需要在 beforeAll 或每个变量中创建一个变量。

describe('some test', () => {
beforeAll(() => {
const foo = createFoo({}, {});
});

it('returns something', () => {
// how to access foo?
});
});

如果我这样做,我将无法在 it 测试中访问 foo,因为它只存在于 beforeAll 范围内。

为了能够访问我需要的地方,我必须在 describe 中声明 foo:

describe('', () => {
let foo;

或者使用

this.foo =

这两种方法的问题是我丢失了类型信息。而且我没有针对此类函数的返回类型的显式接口(interface)。

有没有办法在某个地方声明 foo 以便我以后可以访问它并且不会丢失类型信息?

最佳答案

您可以使用 non-null assertion operator (!) 放宽非空约束。

describe('some test', () => {
let foo!: SomeType;
beforeAll(() => {
foo = createFoo({}, {});
});

it('returns something', () => {
expect(foo.bar).toBe(true);
});
});

关于typescript - 如何在 beforeAll 测试中创建类型变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47192329/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com