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

Encoding objects with oneof and undefined vs null #808

Closed
SkeLLLa opened this issue May 25, 2017 · 3 comments
Closed

Encoding objects with oneof and undefined vs null #808

SkeLLLa opened this issue May 25, 2017 · 3 comments

Comments

@SkeLLLa
Copy link

SkeLLLa commented May 25, 2017

protobuf.js version:6.7.3

Here is example proto file that describes message format that could contain one of some Types in body.

syntax = "proto3";

import "Type1.proto";
import "Type2.proto";
import "Type3.proto";
...
import "Type100500.proto";

package pack;

message MyMessage {
    string head = 1;
    oneof body {
        Type1 Type1 = 2;
        Type2 Type2 = 3;
        Type3 Type3 = 4;
...
        Type100500 Type100500 = 1005001;
    }
}

Proto files are compiled into js with pbjs.
Later in typescript:

import * as proto from 'my-static-protobuf-schemas';

const encode(type: string, payload: any): ArrayBuffer {
  const message = proto.pack.MyMessage.create({
      head: 'my-message-header',
      body: type,
      [type]: payload
    } as proto.pack.MyMessage$Properties);
  return proto.pack.MyMessage.encode(message).finish()
}

And here typescript throws error

Error:TS2345:Argument of type 'MyMessage' is not assignable to parameter of type 'MyMessage$Properties'.
  Types of property 'Type1' are incompatible.
    Type 'Type1$Properties | null' is not assignable to type 'Type1$Properties | undefined'.
      Type 'null' is not assignable to type 'Type1$Properties | undefined'.

Should I set to null all 100499 objects or there is some way to do that automatically?

@dcodeIO
Copy link
Member

dcodeIO commented Jun 8, 2017

If I'm not mistaken, your encode method should be generic or something.

const encode<T>(type: string, payload: T): ArrayBuffer {
  const message = proto.pack.MyMessage.create({
      head: 'my-message-header',
      body: type,
      [type]: <T>payload
    } as proto.pack.MyMessage$Properties);
  return proto.pack.MyMessage.encode(message).finish()
}

Haven't looked through this in detail, though, as it seems to be a TypeScript usage issue.

@Alexendoo
Copy link

It is a typescript/jsdoc issue yeah, it's because the type of an embedded message is IMessage|null rather than IMessage|undefined (or Message$Properties|... for 7.x)

@dcodeIO
Copy link
Member

dcodeIO commented Jun 9, 2017

See also: #826

@dcodeIO dcodeIO closed this as completed Jun 9, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants