Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign type to destructured variable that is also renamed

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.

like image 793
jhpratt Avatar asked Nov 07 '22 06:11

jhpratt


1 Answers

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.

like image 88
y2bd Avatar answered Nov 15 '22 10:11

y2bd