How can I use destructuring assignment while assigning to a new variable name and set a type? An example of this is here:
const {
Script: script, // string
EstimatedDuration: estimated_duration, // number
ActualDuration: actual_duration, // number
} = response.data[0];
My first instinct was to add <string>
or as string
to the RHS, which didn't work. Trying other variations failed as well.
Is this something that is possible, or am I SOL with regard to type checking on these variables? I'd like to use destructuring and not const script: string = response.data[0].Script
and similar.
You can do it if you're willing to type everything out twice.
// replace with your response object above
declare const responseObject: {
Script: any,
EstimatedDuration: any,
ActualDuration: any,
};
const {
Script: script,
EstimatedDuration: estimated_duration,
ActualDuration: actual_duration,
}: {
Script: string,
EstimatedDuration: number,
ActualDuration: number
} = responseObject;
console.log(script, estimated_duration, actual_duration);
At that point though you're just writing the actual type declaration, so you could also make that type below an interface
somewhere for easy access.
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