sindresorhus / is

Type check values
MIT License
1.68k stars 109 forks source link

Add `is.enumCase` and `assert.enumCase` #150

Closed olivierbeaulieu closed 2 years ago

olivierbeaulieu commented 2 years ago

Fixes https://github.com/sindresorhus/is/issues/148

Turns out typing this correctly was a bit trickier than I initially expected, since enums are both a value and a type.

Given this:

enum Direction {
    Asc = 'asc',
    Desc = 'desc'
}
const input: string = 'asc';
assert.enumCase(input, Direction);

If assert.enumCase was typed to return asserts value is T (T being the inferred type of Direction), the asserted type of input would become string & typeof Direction, which is no good.

Typing it as asserts value is T[keyof T] instead did the trick, making input be typed as Direction.

olivierbeaulieu commented 2 years ago

Suggestions applied, thanks!

papb commented 2 years ago

Hello, I think there should have been a test case to verify that assert.enumCase really narrows the type, shouldn't it? The added test is runtime-only...

olivierbeaulieu commented 2 years ago

I thought about added this in - but I noticed that none of the other test suites did the same, so I left it out. Happy to add this in if the maintainers see the value.