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

时间:2018-08-22 16:13:20

标签: typescript tslint

我试图确保我使用的对象没有被修改,但是令我惊讶的是,看来打字稿允许将只读对象传递给未指定参数为只读的函数。例如:

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"
}

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

1 个答案:

答案 0 :(得分:1)

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

相关问题