【问题标题】:Typescript readonly everywhere toggle? (function parameters)Typescript readonly到处切换? (功能参数)
【发布时间】:2021-11-27 04:44:09
【问题描述】:

有没有什么方法可以通过宏库、eslint 规则、tsconfig 设置、魔术global.d.ts 文件或其他方式使函数参数默认为只读?

// I want the compiler to turn this:
function foo(a: A[], b: Record<string, string> {
}
// Into this
function foo(a: ReadonlyArray<A>, b: Readonly<Record<string, string>> ) {
}

【问题讨论】:

  • 您想要将您的代码自动转换为invalid TypeScript 的东西吗?没有办法说readonly b: number 作为函数参数。你是什​​么意思?应该允许没有人为函数体内的b 变量重新赋值?如果是这样,则没有这样的功能,ReadonlyArray&lt;A&gt; 也不会为a 这样做。我糊涂了;帮助!
  • 也许您正在寻找eslint.org/docs/rules/no-param-reassign?但这不是任何 TS 语法都能实现的。
  • 对不起,忽略number 的情况。只考虑可变参数。当我开始写这个问题时,我有foo(args: {a: number, b: string})。那个 eslint 规则似乎很有用,但我的 Q 是关于让函数不改变可变参数。
  • 您想要将Record&lt;string, string&gt; 转换为ReadonlyMap&lt;string, string&gt; 的东西吗?这些是完全不同的数据结构。转换是否也应该修改属性访问,以使b.bar 之类的东西变成b.get("bar")?您能否三重检查您的要求并确保您问题中的代码构成minimal reproducible example

标签: typescript macros immutability readonly


【解决方案1】:

查看no-param-reassign ESLint 规则:

此规则旨在防止因修改或重新分配函数参数而导致的意外行为。

但是这不能替代readonly

/* eslint no-param-reassign: ["error", { "props": true, "ignorePropertyModificationsForRegex": ["^mut"] }] */
function f(n: number, nums: number[], o: { p: string }, mutArr: number[]) {
    n = 10 // error
    n++ // error
    for (n in nums) { } // error
    nums[1] = 10 // error
    nums.push(1) // passes
    nums.sort() // passes
    o.p = 'foo' // error
    mutArr[0] = 10 // passes
}

【讨论】:

  • 这很棒,它也适用于对象/数组属性。它缺少的主要是数组方法。非常感谢,我会更新示例。
  • 是的,谢谢你提到卢克。我已经更新了答案。
【解决方案2】:

在 typescript github repo 中有一个开放的功能请求正在积极讨论这个功能:

https://github.com/microsoft/TypeScript/issues/42357

看起来如何处理无类型库代码的问题使该功能变得复杂,因此他们可能需要一段时间才能决定是否添加它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2023-01-04
    • 2017-11-12
    • 2021-11-15
    • 1970-01-01
    相关资源
    最近更新 更多