Readonly<[]>与ReadOnlyArray<>的区别及性能优劣对比
Readonly vs ReadonlyArray in TypeScript: Differences & Performance
Great question! Let’s break down how these two TypeScript constructs differ, then tackle the performance question head-on.
Core Differences
First, let’s clarify what each one does, using your code examples as context:
Target Collection Type & Structure
ReadonlyArray<T>is a specialized type for variable-length arrays. Your Code 1:
This works perfectly becauselet readonlyArray: ReadonlyArray<string | number> = ["test", 1, 1];ReadonlyArraydoesn’t enforce a fixed length—it just ensures you can’t mutate the array (nopush(),pop(), etc.) and that all elements are either strings or numbers.Readonly<T>is a generic utility that makes all properties of a given type readonly. When you use it on a tuple like[string, number](Code 2):
This is actually a TypeScript error! The original tuplelet readonlyArray: Readonly<[string, number]> = ["test", 1, 1];[string, number]expects exactly 2 elements, and wrapping it inReadonlydoesn’t change that length constraint.Readonly<tuple>preserves the tuple’s fixed length and type order—only making elements immutable.
Type Safety Guarantees
- With
ReadonlyArray<string | number>, any index access (likereadonlyArray[0]) will return a union type (string | number), since TypeScript can’t know which type is at which position. - With
Readonly<[string, number]>, index access is strictly typed:readonlyArray[0]is guaranteed to be a string,readonlyArray[1]a number. This is a huge win for type safety when you need fixed-position values.
- With
Method Availability
- Both types expose only non-mutating array methods (like
map(),filter(),forEach()), since mutating methods (push(),splice()) are excluded at the type level. ButReadonlyArrayis purpose-built for this, whereasReadonly<tuple>inherits this behavior because tuples are array subtypes.
- Both types expose only non-mutating array methods (like
Performance: Is One Better?
The short answer: There’s no meaningful runtime performance difference—and any compile-time difference is negligible for most projects. Here’s why:
- All TypeScript type annotations (including
ReadonlyandReadonlyArray) are erased during compilation. They don’t add any runtime code, memory overhead, or execution time costs. At runtime, both variables are just plain JavaScript arrays. - For compile-time performance (how fast TypeScript checks your code),
ReadonlyArraymight have a tiny edge because it’s a specialized type the compiler is optimized to handle. But you’d only notice this in extremely large codebases with thousands of type annotations—for most apps, it’s irrelevant.
Which to Choose?
- Use
ReadonlyArray<T>when you need an immutable, variable-length list of elements of typeT. - Use
Readonly<[T1, T2, ...]>when you need an immutable, fixed-length tuple with specific types in specific positions (and make sure your array matches the tuple’s length!).
内容的提问来源于stack exchange,提问作者Ramesh Rajendran
相关产品推荐
相关产品推荐

