1

When I run this script, TS1136: Property assignment expected. error occurs. How can you fix that ?

here is sample.ts.

const str = 'myKey'
const obj = {
    `${str}`: 'myValue',
};
console.log(obj);
        ^
TSError: ⨯ Unable to compile TypeScript:
sample.ts:3:13 - error TS2349: This expression is not callable.
  Type '{}' has no call signatures.

3 const obj = {
              ~
sample.ts:4:15 - error TS2695: Left side of comma operator is unused and has no side effects.

4     `${str}`: 'myValue',
                ~~~~~~~~~
sample.ts:4:5 - error TS1136: Property assignment expected.

4     `${str}`: 'myValue',
      ~~~
sample.ts:4:13 - error TS1005: ',' expected.

4     `${str}`: 'myValue',
              ~
sample.ts:4:15 - error TS1134: Variable declaration expected.

4     `${str}`: 'myValue',
                ~~~~~~~~~
sample.ts:5:1 - error TS1109: Expression expected.

5 };
  ~

Of course, this code works well.

const obj = {
    'key': 'myValue',
};
console.log(obj);
{ key: 'myValue' }
Hiroaki
  • 47
  • 4
  • Does this answer your question? [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – VLAZ Sep 16 '22 at 06:29

1 Answers1

2

You need to wrap dynamic keys in [] to make them work.

const str = 'myKey'
const obj = {
    [`${str}`]: 'myValue',
};
console.log(obj);

This is called Computed Property Names

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34