It seems that what I am trying to do is not possible, but I really hope it is.
Essentially, I have two interfaces, and I want to annotate a single function parameter as the combination of both of them.
interface ClientRequest { userId: number sessionKey: string } interface Coords { lat: number long: number }
And then, in the function, I want to do something like this:
function(data: ClientRequest&Coords) { ... }
So that my 'data' object could contain all of the members from both types.
I saw something referenced in a spec preview, under "Combining Types' Members", but it seems like this hasn't made it in yet.
If it isn't possible, my solution might look like this:
interface ClientRequest<T> { userId: number sessionKey: string data?: T } function(data: ClientRequest<Coords>) { ... }
Which would work in this case, although it's not as dynamic as I would like. I would really like to be able to combine multiple (2+) types in the annotation itself:
function(data: TypeA&TypeB&TypeC) { ... }
I would guess that the conventional solution is to define a type that extends those types, although that seems less flexible. If I want to add a type, I would have to either
Any TypeScript experts care to point me in the right direction?
TypeScript allows merging between multiple types such as interface with interface , enum with enum , namespace with namespace , etc.
TypeScript has the ability to understand variables that can have multiple types. For example, here is some normal JavaScript code: This is allowed in TypeScript by default, because var y (by itself) gives y a type of any , meaning anything. So we can assign anything, for example value or object, to y .
To merge two interfaces with TypeScript, we can use extends to extend multiple interfaces. to create the IFooBar that extends IFoo and IBar . This means IFooBar has all the members from both interfaces inside.
TypeScript allows you to define multiple types. The terminology for this is union types and it allows you to define a variable as a string, or a number, or an array, or an object, etc. We can create union types by using the pipe symbol ( | ) between each type.
The specific answer to your question is: no, there is not a single inline annotation to signify combined or extended types.
The best practice for the problem you are trying to solve would be to create third type that would extend the other two.
interface IClientRequestAndCoords extends IClientRequest, ICoords {} function(data: IClientRequestAndCoords)
UPDATE 2018-10-30
TypeScript now has type intersections. So you can now simply do:
interface ClientRequest { userId: number sessionKey: string } interface Coords { lat: number long: number } function log(data: ClientRequest & Coords) { console.log( data.userId, data.sessionKey, data.lat, data.long ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With