在TS中的const assertion
:
另一件要记住的事情是常量上下文不会立即 将表达式转换为完全不可变的.
我不能理解TS为什么不能使它不可变.理想情况下,它应该抛出错误.
let arr = [1, 2, 3, 4];
let foo = {
name: "foo",
contents: arr,
} as const;
foo.name = "bar"; // error!
foo.contents = []; // error!
foo.contents.push(5); // ...works!
如果我们在foo
对象内将数组值作为文字添加,则它是有效的:
let foo = {
name: "foo",
contents: [1, 2, 3, 4],
} as const;
foo.name = "bar"; // error!
foo.contents = []; // error!
foo.contents.push(5); // NOW THROW ERROR
这是如何工作的,don’t immediately convert and expression
到底是什么意思?