Skip to content

Commit

Permalink
docs: add OneofValue type helper (#1034)
Browse files Browse the repository at this point in the history
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

```proto
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;
  }
}
```

```typesecript
// pass by argument
foo<P extends PaloadNames>(
  payload: OneOfValue<LogPayload['payload'], P>
) {
  const req: LogPayload = {
    createdAt: new Date().toUTCString(),
    payload,
  };

  send(req);
}
```

```typescript
// 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',
  },
});
```

Signed-off-by: clucle <wjdenwls123@gmail.com>
  • Loading branch information
clucle committed Apr 19, 2024
1 parent 7f36a59 commit 7c3ac9f
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.markdown
Expand Up @@ -796,6 +796,14 @@ type OneOfCase<T, K extends OneOfCases<T>> = T extends {
}
? T[U]
: never;

/** Extracts the specific type of a value type from a oneOf field */
export type OneOfValue<T, K extends OneOfCases<T>> = T extends {
$case: K;
[key: string]: unknown;
}
? T
: never;
```

# Default values and unset fields
Expand Down

0 comments on commit 7c3ac9f

Please sign in to comment.