Typescript 后续变量声明必须具有相同的类型。任何

Typescript 后续变量声明必须具有相同的类型。任何,typescript,ava,Typescript,Ava,我使用的是ava(无链接,因为我不允许使用超过2个的链接,没有通用的方法。在您的特殊情况下,您可以创建一个新的TestContext,例如,代替 export type ContextualTest = (t: ContextualTestContext) => PromiseLike<void> | Iterator<any> | Observable | void; 这大部分是未经测试的,因此如果有一些问题,请告诉我。在下一版本的ava中可以键入上下文。然后您

我使用的是ava(无链接,因为我不允许使用超过2个的链接,没有通用的方法。在您的特殊情况下,您可以创建一个新的
TestContext
,例如,代替

export type ContextualTest = (t: ContextualTestContext) => PromiseLike<void> | Iterator<any> | Observable | void;

这大部分是未经测试的,因此如果有一些问题,请告诉我。

在下一版本的ava中可以键入上下文。然后您可以执行以下操作:

interface MyTestFunction<T> {
    (name : string, run : MyContextualTest<T>)
}

import {test as avaTest} from 'ava';
const test : MyTestFunction<IMyContext> = avaTest;
import * as ava from 'ava';

function contextualize<T>(getContext: () => T): ava.RegisterContextual<T> {
    ava.test.beforeEach(t => {
        Object.assign(t.context, getContext());
    });

    return ava.test;
}

const test = contextualize(() => {
    return { foo: 'bar' };
});

test.beforeEach(t => {
    t.context.foo = 123; // error:  Type '123' is not assignable to type 'string'
});

test.after.always.failing.cb.serial('very long chains are properly typed', t => {
    t.context.fooo = 'a value'; // error: Property 'fooo' does not exist on type '{ foo: string }'
});

test('an actual test', t => {
    t.deepEqual(t.context.foo.map(c => c), ['b', 'a', 'r']); // error: Property 'map' does not exist on type 'string'
});

否则,TypeScript编译器会认为
t.context
是一个承诺,尽管它不是@despablue您能为您的用例提出一个问题吗?也许我们可以接受
test()
签名中的泛型。@FinnO这在技术上是有效的,但是如果我想使用
test
函数本身定义的函数的话(比如
test.beforeach
)我必须重新定义所有声明。大约有1700个声明。
import * as ava from 'ava';

function contextualize<T>(getContext: () => T): ava.RegisterContextual<T> {
    ava.test.beforeEach(t => {
        Object.assign(t.context, getContext());
    });

    return ava.test;
}

const test = contextualize(() => {
    return { foo: 'bar' };
});

test.beforeEach(t => {
    t.context.foo = 123; // error:  Type '123' is not assignable to type 'string'
});

test.after.always.failing.cb.serial('very long chains are properly typed', t => {
    t.context.fooo = 'a value'; // error: Property 'fooo' does not exist on type '{ foo: string }'
});

test('an actual test', t => {
    t.deepEqual(t.context.foo.map(c => c), ['b', 'a', 'r']); // error: Property 'map' does not exist on type 'string'
});
function contextualize<T>(getContext: () => Promise<T>): ava.RegisterContextual<T> {
    ava.test.beforeEach(async t => {
        Object.assign(t.context, await getContext());
    });

    return ava.test;
}

const test = contextualize(() => {
    const db = await mongodb.MongoClient.connect('mongodb://localhost:27017')

    return { db }
});