有没有办法防止将只读参数传递给非只读函数?

Is there a way to prevent passing readonly params into non-readonly functions?

我试图确保我使用的对象没有被修改,但我惊讶地发现似乎打字稿允许将只读对象传递给未指定参数为只读的函数.例如:

function testFunc1(obj: { readonly s: string }) {
  testFunc2(obj)   // no error <- would expect an error here as well
  obj.s = "blah"  // error: Cannot assign to 's' because it is a constant or a read-only property.
}

function testFunc2(obj: {s: string}) {
  obj.s = "blah"
}

在这种情况下是否可以打开设置或其他东西以便发生错误?

没有这样的设置,也没有我知道的任何解决方法。参见open suggestion。可能为此编写一个 tslint 规则,但需要基本上复制可分配性检查逻辑,以便在所有正确的位置检查 readonly。使用 TypeScript 编译器的修改版本可能更实用。