개발/일상
ts-proto 에 오픈소스 기여
clucle
2024. 4. 20. 16:33
https://github.com/stephenh/ts-proto/pull/1034
docs: add OneofValue type helper by clucle · Pull Request #1034 · stephenh/ts-proto
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 ...
github.com
proto 파일을 typescript 로 변환해주는 ts-proto 프로젝트에 기여했습니다.
protobuf 의 oneof field 를 변환한 결과로 union type 이 반환되는데, 이 타입을 지정할 수 있는 type helper 를 추가했습니다.
/** 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;
이 helper 를 사용하면 아래와 같이 oneof 로 지정한 필드중 하나를 타입으로 지정할 수 있습니다.
// pass by argument
foo<P extends PaloadNames>(
payload: OneOfValue<LogPayload['payload'], P>
) {
const req: LogPayload = {
createdAt: new Date().toUTCString(),
payload,
};
send(req);
}
// Usage
// Good
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'.
foo({
$case: 'logout',
login: {
accountId: 'accountId',
},
});