Software Imagineer's blog

Using destructuring syntax in TypeScript. Bonus performance tips

Sun Nov 04 2018

Destructing is a lesser known and used syntactic sugar of TypeScript. It can make your code more concise when working with arrays and objects.

Object destructuring

Object destructuring helps to create new variables based on selected properties of an object.

    const car = {make: "Tesla", model:"Model X", year: "2018"};
    const {make, model} = car;
    console.log(make, model);
    // Console: Tesla Model X
    
    // Equivalent JavaScript code:
    var car = { make: "Tesla", model: "Model X", year: "2018" };
    var make = car.make, model = car.model;
    console.log(make, model);

Object destructuring also supports rest parameter. Performance Warning: generating "rest" object is much more expensive and resulting JavaScript code will need to iterate over object properties. Use "rest" when destructuring sparingly and always measure your generated JavaScript performance.

    const car = {make: "Tesla", model:"Model X", year: "2018"};
    const {make, ...other} = car;
    console.log(make, other);
    // Console: Tesla {model: "Model X", year: "2018"}

Array destructuring

Array destructuring works very similarly to object destructuring, but instead of objects works with arrays. Destructuring an array is especially useful when entries in the array represent different concepts instead of being a collection of the same entity. Code snippet below shows how an array destructuring could be useful when building console application where console parameters are often represented as an array.

    const params = ["start", "game", "Dota2"];
    const [command, param1, param2] = params;
    console.log(command, param1, param2);
    // Console: start game Dota2

    // Equivalent JavaScript code:
    var params = ["start", "game", "Dota2"];
    var command = params[0], param1 = params[1], param2 = params[2];
    console.log(command, param1, param2);

Rest parameter concept also works with arrays. Performance warning: to create "rest" array, slice method will be used and will result in a partial copy of an array.

    const params = ["start", "game", "Dota2"];
    const [command, ...other] = params;
    console.log(command, other);
    // Console: start game Dota2

    // Skipping entries:
    const [a,,b] = params;
    console.log(a, b);
    // Console: start Dota2

Summary

Destructuring is quite powerful feature in TypeScript, saving developers from mindless variable declaration and making the code more readable. But at the same time, destructuring has a hidden cost when "rest" syntax is used. Always check generated JavaScript code when using TypeScript syntactic sugar features to avoid performance surprises in the production code.