1

I'm wondering how you can assert the type of multiple variables when using destructuring in TypeScript.

Consider:

const { OneTypeOfObject, AndAnother } = ProtoBuf.loadProtoFile('./ohYesProtobufs.proto').build('iAmANameSpace');

How can I assert that OneTypeOfObject has a type of OneType and AndAnother has a type of OtherType?

I can make them all any like this:

const { OneTypeOfObject, AndAnother } = <any>ProtoBuf.loadProtoFile('./ohYesProtobufs.proto').build('iAmANameSpace');

What I'd actually like to do is something like this:

const { <OneType>OneTypeOfObject, <OtherType>AndAnother } = ProtoBuf.loadProtoFile('./ohYesProtobufs.proto').build('iAmANameSpace');

There's clearly been thought about this sort of thing:

https://github.com/Microsoft/TypeScript/commit/7a74d9f8d021f50201765d2170af8d249af90320

But I can't find the answer based on what I've seen....

Update

I tried both of David's approaches but neither worked. This is the code used for approach 2:

interface OneType extends ProtoBuf.ProtoBuf {
  new(): any;
}

interface OtherType extends ProtoBuf.ProtoBuf {
  new(): any;
}

const { <OneType>OneTypeOfObject, <OtherType>AndAnother } = ProtoBuf.loadProtoFile('./ohYesProtobufs.proto').build('iAmANameSpace');

It caused this error:

Type 'ProtoBuf' is not assignable to type '{ OneTypeOfObject: OneType; AndAnother: OtherType; }'. Property 'OneTypeOfObject' is missing in type 'ProtoBuf'.

1 Answer 1

1

Desturcturing with types was confusing to me at first as well. There are there ways you could accomplish this.

The easiest have ProtoBuf.loadProtoFile('./ohYesProtobufs.proto') return the appropriate type (which I realize isn't always possible or easy).

OR

const { OneTypeOfObject, AndAnother } = <{ OneTypeOfObject: TypeA; AndAnother : TypeB }> ProtoBuf.loadProtoFile('./ohYesProtobufs.proto');

OR

const { OneTypeOfObject, AndAnother } : { OneTypeOfObject: TypeA; AndAnother : TypeB } = ProtoBuf.loadProtoFile('./ohYesProtobufs.proto');

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

3 Comments

Actually that didn't work David - I'll update my question to clarify.
It's hard to say with the example as it exists. Does ProtoBuf.loadProtoFile('./ohYesProtobufs.proto').build('iAmANameSpace') return an object both the values you're looking for?
It does - but that's not part of the protobufjs definition.

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.