denoland / denoland/std

Type narrowing for beforeAll and beforeEach

Open
#6,241 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
3.6k
Forks
681
PR merge metrics
No merged PRs in 30d

Description

Similar to #6219, it would be nice (but very low priority)[^1] if `beforeAll()` / `beforeEach()` transmitted type narrowing information.

Currently, the code below produces a warning that `foo` could be undefined, despite it being initialized in `beforeAll`:

```ts
import { test, beforeAll } from '@std/testing/bdd'; // test doesn't have .only or .skip, WTF - https://github.com/denoland/std/issues/6220
import { assertExists } from '@std/assert';

let foo: string | undefined;

beforeAll(() => {
foo = 'x';
});

test('type narrowing', () => {
// assertExists(foo);
const bar: string = foo; // <-- Type string | undefined is not assignable to type string; Type undefined is not assignable to type string
});
```

**Describe alternatives you've considered**

Moving test initialization code to the top level.

[^1]: It's unclear why `beforeAll` would still be useful given the existence of TLA, aside from backwards/Jest compatibility, so I submitted a [PR recommending top-level code](https://github.com/denoland/std/pull/6240).

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.