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

docs: add OneofValue type helper #1034

Merged
merged 1 commit into from
Apr 19, 2024

Conversation

clucle
Copy link
Contributor

@clucle clucle commented Apr 18, 2024

ref: #1023

In previous helper, it is not possible to construct a message with the oneof field passed as a function argument.

This helper allows for strict type checking and construct message using oneof fields as an argument.

Example

syntax = "proto3";

package logs;

message SignUp {
    string name = 1;
}

message Login {
    string account_id = 1;
}

message Logout {
    string account_id = 1;
    string reason = 2;
}

message LogPayload {
  string created_at = 1;
  oneof payload {
    SignUp signup = 2;
    Login login = 3;
    Logout lougout = 4;
  }
}
// pass by argument
foo<P extends PaloadNames>(
  payload: OneOfValue<LogPayload['payload'], P>
) {
  const req: LogPayload = {
    createdAt: new Date().toUTCString(),
    payload,
  };

  send(req);
}
// Usage

// Good
this.foo( {
  $case: 'login',
  login: {
    accountId: 'accountId',
  },
});

// Build Fail because case and field is not matched
// Argument of type '{ $case: string; login: { accountId: string; }; }' is not assignable to parameter of type 'never'.
this.foo( {
  $case: 'logout',
  login: {
    accountId: 'accountId',
  },
});

We can't use oneof field directly.

This helper allows for strict type checking and passing oneof fields as an argument

Signed-off-by: clucle <wjdenwls123@gmail.com>
@stephenh
Copy link
Owner

Nice, thanks!

@stephenh stephenh merged commit 7c3ac9f into stephenh:main Apr 19, 2024
3 checks passed
@stephenh
Copy link
Owner

🎉 This PR is included in version 1.173.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants