不可变的函数参数打字稿

时间:2020-09-08 12:07:02

标签: typescript

有没有一种方法可以使函数参数的打字稿保持不变? (与Java和final相同)

示例:

function add(a: number, b: number): number {
    a = 5; // possible
    return a + b;
}

我正在搜索的内容,例如:

function add(a: ???, b: ???): number {
    a = 5; // not possible because it would be immutable
    return a + b;
}

出于明确性,我正在搜索此函数是否可以修改我的参数。

2 个答案:

答案 0 :(得分:1)

这有点hacky,但是您可以像这样强制执行

function add(...params: readonly [a: number, b: number]): number {
  const [a, b] = params;
  a = 5;
//^^^^^
//Cannot assign to 'a' because it is a constant.

  return a + b;
}

ab现在是const的蚂蚁,因此是不可变的。

但是请注意,尽管paramsreadonly,但这只能阻止您执行推入或拼接元组数组之类的操作。它不会阻止您完全重新分配阵列

答案 1 :(得分:1)

除了Aron的答案,您还可以允许add接受0 .. n 参数并将其设置为只读:

function add(...args: readonly number[]): number {
    args[0] = 123; // not allowed!

    return args.length === 0 ? 0 
        : args.length === 1 ? args[0] 
        : args.reduce((a, b) => a + b);
}

add() // 0
add(123) // 123
add(123, 456) // 579
add(123, 456, 789) // 1368

...再次,它很hacky,但是可以用。