说我正在使用以下类型的模块:
interface AwesomeLibrary {
name: string;
query: Object;
}
我想将query
类型转换为另一个界面:
interface Query {
startDate: string;
endDate: string;
showAll: boolean;
}
让我们说有一个函数回调给我AwesomeLibrary
。我想将query
强制转换为Query
。现在这就是我的全部:
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;
}
思想?
答案 0 :(得分:1)
你可以像这样输入:
(response.query as Query).startDate = (new Date()).toUTCString();
或者你可以有另一个变量:
let response2 = response as AwesomeLibrary & { query: Query };
response2.query.startDate = (new Date()).toUTCString();
您还可以接收此类型的参数:
function functionCb(response: AwesomeLibrary & { query: Query }) {
response.query.startDate = (new Date()).toUTCString();
}
但是在调用此函数时你需要进行转换。