Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
qc00 opened this issue Jun 26, 2018 · 2 comments
Closed

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

qc00 opened this issue Jun 26, 2018 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@qc00
Copy link

qc00 commented Jun 26, 2018

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)
@mhegazy
Copy link
Contributor

mhegazy commented Jun 26, 2018

This was one of the proposals we discussed when adding conditional type support. The general consensuses was that we need a new readonly type operator (tracked by #10725). the type duplication for every entity causes other problems in inference, overload resolution, and in type comparisons.

I am going to say this is a duplicate of #10725, since #10725 fulfills the underlying scenario.

@mhegazy mhegazy added the Duplicate An existing issue was already created label Jun 26, 2018
@mhegazy
Copy link
Contributor

mhegazy commented Jun 26, 2018

I should also add that you can always add this type in your project and use it as a wrapper for Readonly, but we do not have plans to add it to the standard library at the time being.

@qc00 qc00 closed this as completed Jun 26, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants