Search code examples
angulartypescriptngrx

What is the meaning of ngrx adapter selector syntax?


I have found following example of ngrx adapter:

export const {
  selectAll: selectAllItems
} = adapter.getSelectors<State>(state => state.items);

But I don't understand what is assigned to what here. Especially the notation of a type: const {sth: foo} = bar; Would someone be so nice, to advise me, please :)


Solution

  • This is the syntax for Object Destruction in Typescript and assigning to new variable names:

    Your code roughly translates to classic javascript as (parsed using online parser):

    const selectAllItems = adapter.getSelectors(state => state.items).selectAll;
    

    Another example copied from TS Docs:

    // structure
    const obj = {"some property": "some value"};
    
    // destructure
    const {"some property": someProperty} = obj;
    console.log(someProperty === "some value"); // true
    

    This is akin to Object destruction in Javascript like:

    const {x, y} = {x: 10, y: 20};
    console.log(x, y); // 10 20
    

    Or a property can be unpacked from an object and assigned to a variable with a different name than the object property. (From MDN Docs)

    var o = {p: 42, q: true};
    var {p: foo, q: bar} = o;
    
    console.log(foo); // 42 
    console.log(bar); // true
    

    Here, for example, var {p: foo} = o takes from the object o the property named p and assigns it to a local variable named foo.