Skip to content

Subsequent variable declarations must have the same type when trying to type t.context [TypeScript] #1291

@despairblue

Description

@despairblue

Copied from StackOverflow

Description

I use ava with typescript and want to type ava's test context. It's typed as any in ava's definition file.

@novemberborn suggested adding a generic to the test() signature

Test Source

What I specifically want is that the typescript compiler knows that t.context is of the type {foo: number} in the following test:

import test from 'ava'

test.beforeEach((t) => {
  t.context = { foo: 5 }
})

test('Is context typed', (t) => {
  // uncaught typo
  t.is(t.context.fooo, 5)
})

I tried to use declaration merging to do this, but it fails with TS2403: Subsequent variable declarations must have the same type. Variable 'context' must be of type 'any', but here has type '{ foo: number; }'. :

declare module 'ava' {
    interface ContextualTestContext {
      context: {
        foo: number,
      }
    }
}

test.beforeEach((t) => {
  t.context = { foo: 5 }
})

test('Is context typed', (t) => {
  // uncaught ypo
  t.is(t.context.fooo, 5)
})

Is there a way to do this without casting the context all the time like so:

interface IMyContext {
  foo: number
}

test.beforeEach((t) => {
  t.context = { foo: 5 }
})

test('Is context typed', (t) => {
  const context = <IMyContext> t.context
  // caught typo
  t.is(context.fooo, 5)
})

Error Message & Stack Trace

does not apply

Config

does not apply

Command-Line Arguments

does not apply

Relevant Links

Environment

Tell us which operating system you are using, as well as which versions of Node.js, npm, and AVA. Run the following to get it quickly:

Node.js v6.9.5
darwin 16.4.0
0.18.2
3.10.10

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions