hachyderm.io is one of the many independent Mastodon servers you can use to participate in the fediverse.
Hachyderm is a safe space, LGBTQIA+ and BLM, primarily comprised of tech industry professionals world wide. Note that many non-user account types have restrictions - please see our About page.

Administered by:

Server stats:

8.9K
active users

Is there a tool for #TypeScript that checks static type assertions similar to the following one?

// %inferred-type: (string | number | boolean)[]
const arr = [1, 'a', true];

I have written such a tool but it’s not ready for public consumption ATM, so such a tool already existing would save me the work of publishing what I have.

My tool is loosely similar to unit test runners such as Mocha—it enables static unit tests, if you will.

@rauschma It sounds like the new satisfies operator does what you need (new in v4.9):

> const arr = [1, 'a', true];
undefined
> arr satisfies (string | number | boolean)[]
{{{no typescript error}}}

> const arr2 = [1, 'a', true, new Date()];
undefined
> arr2 satisfies (string | number | boolean)[];
<repl>.ts:8:16 - error TS1360: Type '(string | number | boolean | Date)[]' does not satisfy the expected type '(string | number | boolean)[]'.

@vincentrolfs Alas, it’s not strict enough:

const a = 123;
(a satisfies number | boolean | string); // no error

@vincentrolfs Yes, that looks similar to some of the other suggestions in the replies! I’ll have to think about it—different from what I’m currently doing, with different pros and cons.