5

I'm currently implementing some protocol buffers translation in my typescript project. I've gotten the proto files loaded into the ProtoBuilder (using the typescript definitions file from protobufjs.d.ts) and I've returned a ProtoBuf from the builder.

If I set a breakpoint after I have the ProtoBuf object in a variable named pb, I can call pb.decode(buffer) in the console and it works. TypeScript, however, doesn't like the syntax.

After much poking and prodding, including trying things like:

pb["decode"](buffer)

(This gives Error TS2349 Cannot invoke an expression whose type lacks a call signature.)

I still cannot get the TypeScript compiler like the code.

How do I get from a TypeScript ProtoBuf object to the decode function buried within the MetaMessage object?

If it matters, I'm in Visual Studio 2015 doing this.

edit: I can get around the problem using:

var decoder: any = pb["decode"];
decoder(buffer);

But I would prefer a more elegant solution if one exists.

9
  • I know nothing about protobuf, but in TypeScript, you should be able to do pb['decode'](buffer), or (<any>pb).decode(buffer). Commented May 2, 2016 at 22:18
  • The first option (which apparently had the square braces removed in my question) was not effective, however, assigning var decoder: any = pb['decode']; did allow me a call to decoder(buffer). I'm hoping for a nicer looking answer, so I'll leave it open a bit, but I definitely appreciate the (<any>pb) bit since that's likely to come in handy in the future. Commented May 2, 2016 at 22:34
  • "was not effective"? Did you get a build error? If so, adding that to your question would be quite helpful... Commented May 2, 2016 at 22:37
  • Added the error info to the question. Thanks. Commented May 2, 2016 at 22:57
  • Have you tried pb.decode(buffer)? Commented May 2, 2016 at 23:29

1 Answer 1

2

Working with definition files for existing JavaScript libraries can be tricky, because JavaScript is very loosely defined, whereas TypeScript is quite well defined. Without modifying the existing .d.ts file, or writing your own, the options are limited. Theoretically, the following should work:

pb['decode'](buffer)

But you mentioned it did not. Your workaround of setting an intermediate variable works fine:

var decoder: any = pb["decode"];
decoder(buffer);

This code is similar to the other workaround, which is to just declare pb as any. The following code does this inline:

(<any>pb).decode(buffer);

This code is basically telling the TypeScript compiler to "just pretend pb is something that has a decode method, or whatever".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.