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

Document type helpers for oneOfs #1023

Merged
merged 1 commit into from
Mar 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,28 @@ As this will automatically enforce only one of `field_a` or `field_b` "being set

In ts-proto's currently-unscheduled 2.x release, `oneof=unions` will become the default behavior.

## OneOf Type Helpers

The following helper types may make it easier to work with the types generated from `oneof=unions`:

```ts
/** Extracts all the case names from a oneOf field. */
type OneOfCases<T> = T extends { $case: infer U extends string } ? U : never;

/** Extracts a union of all the value types from a oneOf field */
type OneOfValues<T> = T extends { $case: infer U extends string; [key: string]: unknown }
? T[U]
: never;

/** Extracts the specific type of a oneOf case based on its field name */
type OneOfCase<T, K extends OneOfCases<T>> = T extends {
$case: infer U extends K;
[key: string]: unknown;
}
? T[U]
: never;
```

# Default values and unset fields

In core Protobuf (and so also `ts-proto`), values that are _unset_ or equal to the default value are not sent over the wire.
Expand Down
Loading