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....
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'.
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.