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

OptionalExcept type #811

Open
stabai opened this issue Feb 1, 2024 · 2 comments
Open

OptionalExcept type #811

stabai opened this issue Feb 1, 2024 · 2 comments

Comments

@stabai
Copy link

stabai commented Feb 1, 2024

A common use case of making a Partial of an object, but leaving a few keys as is.

export type OptionalExcept<Type, AsIsKeys extends keyof Type> = Pick<Type, AsIsKeys> & Partial<Omit<Type, AsIsKeys>>;

Example:

interface User {
  username: string;
  isAdmin: boolean;
  dateCreated: Date;
}

function newUser(userOptions: OptionalExcept<User, 'username'>): User {
  return {
    // Default values for optionals (if specified in userOptions, will be overwritten)
    isAdmin: false,
    dateCreated: new Date(),

    // Specified values (including the username, which we kept as required)
    ...userOptions
  };
}

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar
@voxpelli
Copy link
Collaborator

voxpelli commented Feb 2, 2024

I guess this can be achieved somewhat by doing SomeOptional<User, Omit<keyof User, 'username'>> – maybe that's enough?

@stabai
Copy link
Author

stabai commented Feb 2, 2024

Oh, yes, that would work, I hadn't thought of that formulation. I may be misunderstanding the suggested types, but I think it would be like this:

SetOptional<User, Exclude<keyof User, 'username'>>

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

No branches or pull requests

2 participants