Can a typescript parameter be annotated as const?

Viewed 12325

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.

3 Answers

It's not supported yet, but you can upvote this feature request & follow it for any updates in the future: https://github.com/microsoft/TypeScript/issues/18497

In the meantime your best bet is to use a linter rule to make arguments const by default, like ESLint's no-param-reassign rule. In any rare cases where you need an argument to be not const, you can either use eslint-disable-line each place you reassign it, or wrap the whole function in an eslint-disable / eslint-enable pair to make all its arguments non-const.

Typescript doesn't support const in the function parameter yet, but you can do readonly parameters.

Typescript 3.4 added support for readonly arrays and tuples (not objects yet).

Examples:

function foo(arr: readonly string[]) {}

or

function foo(pair: readonly [string, string]) {}

or

function foo(arr: ReadonlyArray<string>) {}

Related