显然,TypeScript允许您通过简单的赋值来从类型中删除readonly修饰符,像这样:
function foo(x: { readonly value: string }) {
x.value = "new value"; // This would fail, as it should
bar(x); // But this is okay?
}
function bar(x: { value: string }) {
x.value = "new value";
}
我觉得这样做会使得意外修改只读字段变得非常容易,或者我漏掉了什么?我是否错误地使用了readonly?在typescript中是否有更严格的替代方案来禁止这种行为?
编辑:由于确实是这样工作的,这里有一个解决方法,虽然它并不完美,但在我的特殊情况下似乎有所帮助:
type ConstAware<T> = { __writable: true } & { [P in keyof T]: T[P] };
type Const<T> = T extends ConstAware<any> ? { readonly [P in Exclude<keyof T, "__writable">]: T[P] } : never;
type Foo = ConstAware<{
value: string;
}>;
function foo(x: Const<Foo>) {
let y: Foo = x; // Not allowed, yay
y.value = "new value";
}