'TypeScript: Can I assert a value to a type with different property names?
I am working with an API and a web framework.
I have an interface IResponse. It looks something like this
interface IResponse {
Id: string;
Name: string;
}
When I get an API response, I get an array and assert the value as IResponse[]
However, the Web Framework I'm using requires me to convert this IResponse[] to an IComboBoxOption[] which has the following interface:
interface IComboBoxOption {
key: string;
text: string;
}
Right now, I am converting it like this:
const convertedResults: IComboBoxOption[] = [];
const results = await APICall(productsRequest) as IResponse[];
results.forEach(r => {
convertedResults.push({
key: r.Id,
text: r.Name,
});
}
However, there are a large amount of results and the forEach loop takes too long. Ideally, I would like to skip the conversion step all together, and directly assert the API return value as an IComboBoxOption[].
Is this at all possible?
Note: I have no control over the property names returned by the API, and I must use this Web Framework.
Solution 1:[1]
There is no way to change the names of the properties without iterating over each value. But you can use a method that has more performance:
Using ES6 array methods tend to work faster https://leanylabs.com/blog/js-forEach-map-reduce-vs-for-for_of/
try using this:
const convertedResults: IComboBoxOptions = results.map((r) => ({
key: r.Id,
text: r.Name,
}));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Wheale |
