ARTICLE AD BOX
This is not possible with TypeScript. Properties can be made read-only with the readonly modifier or the Readonly utility type but they cannot be marked as write-only on a type level.
What you can use instead is a method that sets properties but no properties are exposed.
Using a wrapper class:
class WriteOnly<K extends PropertyKey, V> { private _myValues: Partial<Record<K, V>> = {}; public setValue(key: K, value: V) { this._myValues[key] = value; } } const foo = new WriteOnly<string, string>(); foo.setValue("bar", "yes"); // the only thing allowedOr implemented with a Map:
class WriteOnly<K extends PropertyKey, V> { private _myValues: Map<K, V> = new Map<K, V>(); public setValue(key: K, value: V) { this._myValues.set(key, value); } } const foo = new WriteOnly(); foo.setValue("bar", "yes"); // the only thing allowedAlternatively, you can use a Map directly and strip away anything that can change the values inside. This is easily achievable on the type level but you need a function that returns the new Map:
type WriteOnlyMap<K, V> = Pick<Map<K, V>, "set" | "delete" | "clear">; function createWriteOnlyMap<K, V>(): WriteOnlyMap<K, V> { return new Map<K, V>(); }That allows set(), delete(), and clear() to be called but does not allow anything else:
foo.set("bar", "yes"); // allowed foo.delete("bar"); // allowed foo.clear(); // allowed foo.forEach(); // not allowed foo.entries(); // not allowed foo.get("bar"); // not allowed foo.has(); // not allowed for(const entry of foo){} // not allowed