打字稿参数可以注释为const吗?

问题描述 投票:0回答:5

如果我不想在函数作用域内更改参数的值,有什么方法可以用 Typescript 进行注释吗?

我已经尝试过:

function walk(const fileName: string): string[] {
// -----------^
}

但是不起作用。

typescript
5个回答
8
投票

现在没有办法做到这一点,也可能不会,因为在

ES6
中也不可能做到:

如何在JavaScript中使函数参数不变?

这个解决方法无论如何都不适用于 TypeScript。


4
投票

Typescript 尚不支持函数参数中的

const
,但您可以使用
readonly
参数。

Typescript 3.4 添加了对

readonly
数组和元组(还不是对象)的支持。

示例:

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

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

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


4
投票

尚不支持,但您可以投票支持此功能请求并关注它以获取将来的任何更新:https://github.com/microsoft/TypeScript/issues/18497

与此同时,最好的选择是使用 linter 规则默认将参数设置为 const,例如 ESLint 的 no-param-reassign 规则。在极少数情况下,您需要一个参数为 not const,您可以在每个重新分配它的地方使用

eslint-disable-line
,或者将整个函数包装在
eslint-disable
/
eslint-enable
对中,使 all 成为它的参数非常量。


2
投票

带有一些额外字符的简短解决方法已经接近:

function fo(args: {x: number,y: string}): void{
    const {x,y} = args;
    x = 2; // Cannot assign to 'x' because it is a constant.ts(2588)
}
function fa(...args: [x: number,y: string]): void{
    const [x,y] = args;
    x = 2; // Cannot assign to 'x' because it is a constant.ts(2588)
}

但您仍然可以使用

args.x=2
进行覆盖。


0
投票

这可以通过 TypeScript 5.0 版本中的

const
类型参数约束来实现。

function walk<const T extends string>(fileName: T): string {
  // TS is upset here because we're attempting to modify a constant
  fileName = 'my new value';

  // TS knows you're returning a string here
  return fileName;
}

参见:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-0.html#const-type-parameters

注意: 从技术上讲,您可以执行

fileName = fileName;
并且 TS 将编译 - 这与被视为
const
readonly
变量声明略有不同。

© www.soinside.com 2019 - 2024. All rights reserved.