Skip to content

Add a Readonly factory type/wrapper that supports Maps/Sets #25230

Closed
@qc00

Description

@qc00

Search Terms

"readonly" type set

Suggestion

Add something like below to the standard library

type SmartRO<T> =
    T extends ReadonlyArray<any> | ReadonlyMap<any, any> | ReadonlySet<any> ? T :
    T extends Array<infer U> ? ReadonlyArray<U> :
    T extends Map<infer K, infer V> ? ReadonlyMap<K, V> :
    T extends Set<infer U> ? ReadonlySet<U> :
    Readonly<T>;

Use Cases

Often people want to express in the type system that certain value is not to be modified by code accessing them. However, the Readonly<T> wrapper type does not work on Map and Set.

As a result, it's difficult to write a generic type that takes a mutable type argument and use a read-only version in the type body.

Examples

interface Validator<T> {
    isValid(x: SmartRO<T>);
}

Checklist

My suggestion meets these guidelines:

  • [✔] This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • [✔] This wouldn't change the runtime behavior of existing JavaScript code
  • [✔] This could be implemented without emitting different JS based on the types of the expressions
  • [✔] This isn't a runtime feature (e.g. new expression-level syntax)

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions