Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RequireExactlyOne type #55

Merged
merged 9 commits into from Sep 16, 2019
Merged

Add RequireExactlyOne type #55

merged 9 commits into from Sep 16, 2019

Conversation

kainiedziela
Copy link
Contributor

@kainiedziela kainiedziela commented Jul 28, 2019

Fixes #54

Create a type that requires exactly one of the given properties and disallows more. The remaining properties are kept as is.

Use cases

  • Creating interfaces for components that only need one of the properties to display properly.
  • Declaring generic properties in a single place for a single use case that get narrowed down via RequireExactlyOne.

The caveat with RequireExactlyOne is that TypeScript doesn't always know at compile time every property that will exist at runtime. Therefore RequireExactlyOne can't do anything to prevent extra properties it doesn't know about.

Example

import {RequireExactlyOne} from 'type-fest';

type Responder = {
	text: () => string;
	json: () => string;
	secure: boolean;
};

const responder: RequireExactlyOne<Responder, 'text' | 'json'> = {
	json: () => '{"message": "ok"}',
	secure: true
};

Copy link
Contributor

@SamVerschueren SamVerschueren left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is cool, I need it :).

test-d/require-one.ts Outdated Show resolved Hide resolved
Change spaces to tabs
test-d/require-one.ts Outdated Show resolved Hide resolved
source/require-one.d.ts Outdated Show resolved Hide resolved
Co-Authored-By: Dimitri Benin <BendingBender@users.noreply.github.com>
readme.md Outdated Show resolved Hide resolved
@sindresorhus sindresorhus changed the title Add RequireOne Add RequireOne type Aug 3, 2019
@kainiedziela kainiedziela changed the title Add RequireOne type Add RequireExactlyOne type Aug 7, 2019
@BendingBender
Copy link
Collaborator

LGTM

@kainiedziela
Copy link
Contributor Author

@sindresorhus @BendingBender guys?

@sindresorhus sindresorhus merged commit 0a9d935 into sindresorhus:master Sep 16, 2019
@SamVerschueren
Copy link
Contributor

Nice! Thanks for working on this!

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.

RequireOnlyOne type
4 participants