Skip to content

Add is.enumCase and assert.enumCase - #150

Merged
sindresorhus merged 3 commits into
sindresorhus:mainfrom
olivierbeaulieu:main
Jan 17, 2022
Merged

sindresorhus merged 3 commits into
sindresorhus:mainfrom
olivierbeaulieu:main

Conversation

@olivierbeaulieu

@olivierbeaulieu olivierbeaulieu commented Jan 16, 2022 •

Copy link
Copy Markdown
Contributor

Fixes #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.

Comment thread readme.md Resolved
Comment thread readme.md Resolved
@sindresorhus sindresorhus changed the title Added is.enumCase and assert.enumCase Add is.enumCase and assert.enumCase Jan 16, 2022
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
@olivierbeaulieu

olivierbeaulieu commented Jan 16, 2022 •

Copy link
Copy Markdown
Contributor Author

Suggestions applied, thanks!

@sindresorhus
sindresorhus merged commit a5b4017 into sindresorhus:main Jan 17, 2022
@papb

papb commented Jan 18, 2022

Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Contributor Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Proposal: Add support for enum validation

3 participants