Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a typescript parameter be annotated as const?

Tags:

typescript

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.

like image 886
kiewic Avatar asked Jul 13 '17 16:07

kiewic


People also ask

What does const {} mean in TypeScript?

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.

Which items are not proper TypeScript?

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.

Can you pass a type as a parameter TypeScript?

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.

What is const parameter?

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.


1 Answers

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.

like image 185
lilezek Avatar answered Oct 14 '22 18:10

lilezek