From 7c3ac9f215f05841c9a95e0e197795b985b73900 Mon Sep 17 00:00:00 2001 From: clucle Date: Sat, 20 Apr 2024 05:25:42 +0900 Subject: [PATCH] docs: add OneofValue type helper (#1034) ref: https://github.com/stephenh/ts-proto/pull/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

( payload: OneOfValue ) { 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 --- README.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.markdown b/README.markdown index 1b7e8bfc2..062d7f927 100644 --- a/README.markdown +++ b/README.markdown @@ -796,6 +796,14 @@ type OneOfCase> = T extends { } ? T[U] : never; + +/** Extracts the specific type of a value type from a oneOf field */ +export type OneOfValue> = T extends { + $case: K; + [key: string]: unknown; +} + ? T + : never; ``` # Default values and unset fields