Reputation: 36219
Say I'm using a module of the following type:
interface AwesomeLibrary {
name: string;
query: Object;
}
I want to typecast query
into another interface:
interface Query {
startDate: string;
endDate: string;
showAll: boolean;
}
Let's say there is a function callback that gives me the AwesomeLibrary
. I want to then typecast the query
into Query
. Right now this is all I have:
functionCb(response: AwesomeLibrary) {
// This works fine
let query: Query = response.query as Query;
// Now, query.startDate is available
// Do stuff to query
// At the end, I want to send response back to another function, so I do
response.query = query;
otherFunction(response);
// This does not work, but basically what I want:
response.query = response.query as Query;
// Then do stuff to response.query directly
// Here response.query.startDate is not available, instead I have to use response.query['startDate']
// Even this does not work:
let query: Query = response.query as Query;
response.query = query;
}
Thoughts?
Upvotes: 0
Views: 109
Reputation: 164147
You can type cast it like so:
(response.query as Query).startDate = (new Date()).toUTCString();
Or you can have another variable:
let response2 = response as AwesomeLibrary & { query: Query };
response2.query.startDate = (new Date()).toUTCString();
You can also receive the parameter in this type:
function functionCb(response: AwesomeLibrary & { query: Query }) {
response.query.startDate = (new Date()).toUTCString();
}
But then you'll need to cast when calling this function.
Upvotes: 1