Touloudou
Touloudou

Reputation: 2223

Passing const variables to functions in TypeScript

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?

Upvotes: 2

Views: 4029

Answers (1)

baklazan
baklazan

Reputation: 821

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.

Upvotes: 4

Related Questions