You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术咨询:ReadonlySet是否类同C#的ReadOnlyCollection及相关实现

Understanding TypeScript's ReadonlySet

Great question! Let's unpack this step by step, especially since you're drawing a comparison to C#'s ReadOnlyCollection.

First: Is ReadonlySet a collection of read-only properties?

No, that's a common misconception. ReadonlySet isn't about the properties of the items in the set—it's about the set itself being read-only. You can't modify the set's contents (no adding, deleting, or clearing items) through a ReadonlySet reference, which aligns closely with the intent of C#'s ReadOnlyCollection, just for Set instead of list/collection types.

What's the purpose of ReadonlySet?

  • Prevent accidental modification: Use it when you want to expose a set to external code (like via a class getter) but don't want outside code to alter its contents.
  • Enforce immutability in function parameters: If a function only needs to read from a set, declaring the parameter as ReadonlySet makes it clear the function won't modify the input, and TypeScript will enforce that.
  • Align with immutable programming practices: Reduces side effects by restricting write operations where they aren't needed.

How does it work under the hood?

In TypeScript, ReadonlySet is a built-in interface that only includes the read-only methods and properties of a standard Set:

  • Read operations: has(), size, forEach(), keys(), values(), entries()
  • All mutation methods (add(), delete(), clear()) are excluded from the interface.

You don't need to implement it yourself—any standard Set is automatically compatible with ReadonlySet, since Set includes all the members of ReadonlySet plus the mutation methods.

Code examples: Assigning to ReadonlySet<number>

Here are the most common ways to create and assign a ReadonlySet:

1. Assign a regular Set to a ReadonlySet variable

// Create a mutable Set first
const mutableNumbers = new Set<number>([1, 2, 3]);
// Assign it to a ReadonlySet variable—TypeScript will restrict mutation
let readonlySet: ReadonlySet<number> = mutableNumbers;

// This works (read operation)
console.log(readonlySet.has(2)); // true

// This will throw a compile-time error (mutation attempt)
// readonlySet.add(4); // Error: Property 'add' does not exist on type 'ReadonlySet<number>'

2. Directly initialize as ReadonlySet

You can create a Set and assign it directly without an intermediate variable:

let readonlySet: ReadonlySet<number> = new Set([5, 6, 7]);

Even though the underlying object is a mutable Set, TypeScript's type system will block any mutation attempts through the readonlySet reference.

3. Expose a read-only set from a class

A common use case is hiding a mutable internal set behind a ReadonlySet getter:

class Inventory {
  private _items = new Set<string>(["apple", "banana", "cherry"]);

  // Expose only a read-only view to external code
  get items(): ReadonlySet<string> {
    return this._items;
  }

  // Internal method that can modify the set
  addItem(item: string) {
    this._items.add(item);
  }
}

const inventory = new Inventory();
console.log(inventory.items.has("banana")); // true
// inventory.items.delete("apple"); // Compile error: No 'delete' method on ReadonlySet
inventory.addItem("date"); // Works—internal modification is allowed

Comparison to C#'s ReadOnlyCollection

  • Similar intent: Both provide a read-only view of a mutable collection, preventing external modification through the read-only reference.
  • Key difference: C#'s ReadOnlyCollection is a concrete class that wraps an existing collection. In TypeScript, ReadonlySet is an interface—you don't need to wrap anything; a regular Set automatically fits the ReadonlySet type (it's a compile-time check, not a runtime wrapper). Note: Just like in C#, if someone gets access to the underlying mutable Set (e.g., via a private member leak), they can modify it at runtime—but TypeScript's type system prevents this in normal usage.

内容的提问来源于stack exchange,提问作者Ramesh Rajendran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:36:32