简体   繁体   English

如何从不可变对象类型中提取可变对象类型

[英]How to extract mutable object type from immutable object type

I need to create type which extracts just mutable object type from existing immutable object type like: 我需要创建从现有的不可变对象类型中仅提取可变对象类型的类型:

import * as Immutable from 'seamless-immutable'

interface IObjType {
  field: string;
}
type TObjImmType = Immutable.Immutable<IObjType>;

const obj: IObjType = { field: 'val' };
const objImm: TObjImmType = Immutable(obj);

// dummy function to show what I need to do
const getMutable = (immObj: TObjImmType): IObjType => immObj.asMutable();

const result = getMutable(objImm);

So the problem is with getMutable . 所以问题出在getMutable Typescript do not checks did it reeturn mutable or immutable object and I need to force TS to validate this and throw error if immutable is returned. Typescript不检查它是否会再次返回可变或不可变对象,因此我需要强制TS对此进行验证,如果返回不可变对象,则会引发错误。

How to do this? 这个怎么做?

A property being readonly is only a flag for the TS compiler, it does not exist in JavaScript. 只读的属性仅是TS编译器的标志,JavaScript中不存在。

This essentially means that readonly and non-readonly properties are 100% equal functionally, as such there should be no possible means of validating the process of making an object mutable/immutable. 从本质上讲,这意味着只读和非只读属性在功能上是100%相等的,因此,应该没有任何方法可以验证使对象可变/不可变的过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM