0

I have the following code:

type myTuple = [string, (value:string) => void]

function setState(v: string) : myTuple {
    let myState:string = v;
    return [
        myState,
        (a) => myState = a
    ]
}

const [val,setVal] = setState('value1');
console.log(val);
setVal('Change');
console.log(val);

I'm expecting val to be changed to "Change", but instead it remains "value1" after the second console.log.

However, I did find a way to make it work:

type myTuple = [() => string, (value:string) => void ]

function setState(v: string) : myTuple {
    let myState:string = v;
    return [
        () => myState,
        (a) => myState = a
    ]
}

const [val,setVal] = setState('value1');
console.log(val());
setVal('AAP');
console.log(val());

Why is this working?

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
kevin
  • 600
  • 1
  • 13
  • 1
    `[myState, (a) => myState = a]` contains a reference to the _value_ (the string `"value1"`) also referenced by `myState`, not somehow to the _name_ `myState` to track its value as it changes. Maybe run these through e.g. https://pythontutor.com/javascript.html#mode=edit to illustrate the difference (this doesn't support TypeScript, but the types are irrelevant anyway). – jonrsharpe Nov 22 '21 at 10:19

0 Answers0