2

I am learning TypeScript and I am a bit confused by the way it handles const variables. Let's say I define an interface for a number as:

interface MyNumber {
    value: number;
}

and created a const MyNumber

const myNumber: MyNumber = { value: 42 };

I read in the TypeScript documentation that const did not prevent me from modifying the internal state of the object (provided the property is not readonly). However, I did not expect this to compile:

function setToFive(num: MyNumber) {
    num = {
        value: 5
    }
}

console.log(myNumber);
setToFive(myNumber);
console.log(myNumber);

This code prints 42 twice. It looks like the function performs a copy of my const variable and uses that copy within its scope. I find this a bit surprising. Is there a way to trigger a compile-time error instead?

2
  • you could mark the value field as readonly. That gives you a bit more of protection against accidental assignments. Commented Nov 12, 2019 at 15:04
  • Const declaration is not really as immutable as it should be. If a variable holds advanced type ( Object ) you can still change it's properties. Well, if you really want to achieve immutability, you have to use Object.freeze() Commented Nov 12, 2019 at 15:16

1 Answer 1

4

You are reassigning the function parameter num to your new object. You cannot put const in function parameters.

What you are looking for is eslint or something similar. A tool to force best principles on your project with rule no param reassign.

Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I was looking for. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.