Adding a get property that renders in a lightning-datatable

javascriptlightning-datatablelightning-web-components

I have an LWC that takes an object returned from the server-side, makes it mutable by cloning, and then adds a get property via Object.defineProperty:

    const t = {...template};
    Object.defineProperty(
        t,
        'typeAndName',
        { get() { return t.type + ': ' + t.MasterLabel; } }
    );

    // Correct output here
    console.log('typeAndName', t.typeAndName);

But when rendered in a lightning-datatable (actually a lightning-tree-grid that is based on that) column:

        {
            type: 'text',
            fieldName: 'typeAndName',
            label: 'Type and Name',
        },

an empty string always results.

Is this a step too far for LWC given that properties are reactive? Or am I missing something else here?

PS

Just looked at the code again and this cleaner spread syntax version does work so for me so the original question is just of academic interest now:

    const t = {
        ...template,
        get typeAndName() { return t.type + ': ' + t.MasterLabel; }
    };

Best Answer

{ get() { return t.type + ': ' + t.MasterLabel; } }

Should have been:

{ get: function() { return t.type + ': ' + t.MasterLabel; } }

You can also use a template literal here:

{ get: function() { return `${this.type}: ${this.MasterLabel}`; } }

The descriptor object is in normal object syntax, just as you'd say { message: 'Hello World' }.

Here's a working example.