If I do not want the value of a parameter change within a function scope, is there any way to annotate that with Typescript?
I've tried:
function walk(const fileName: string): string[] {
// -----------^
}
But it does not work.
Typescript constants are variables, whose values cannot be modified. We declare them using the keyword const . They are block-scoped just like the let keyword. Their value cannot be changed neither they can be redeclared. Const keyword is part of the es2015 (es6) specification of the javascript.
Number , String , Boolean , Symbol and Object ❌ Don't ever use the types Number , String , Boolean , Symbol , or Object These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code.
To type a function as a parameter, type the function's parameter list and its return value, e.g. doMath: (a: number, b: number) => number . If the function's definition becomes too busy, extract the function type into a type alias.
A constant parameter, declared by the keyword const , is a read-only parameter. This means that we can not modify the value of the constant parameter in the function body. Using the const keyword tells the compiler that the value of that parameter will not be changed inside the function.
There is no way to do it right now, and it may not be, as it is not possible in ES6
either:
How to make function parameter constant in JavaScript?
This workaround doesn't work for TypeScript anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With