TS2539

error TS2539: Cannot assign to defaultName because it is not a variable.

Broken Code ❌

defaults.ts
1
export let defaultName = 'Benny';
main.ts
1
2
3
import {defaultName} from './defaults';

defaultName = 'Sofia';

Fixed Code ✔️

Using the let keyword might lead to the assumption of exporting a variable, but in reality, every export becomes a constant. As we’re aware, constants cannot be reassigned.

To work around this, we can use a little trick with how some types are handled. If we put our defaultName (initially a primitive string type) inside an object (which is a complex type), we can change the value inside the object as it is passed by reference:

defaults.ts
1
2
3
export const defaults = {
defaultName: 'Benny'
};
main.ts
1
2
3
import {defaults} from './defaults';

defaults.defaultName = 'Sofia';