Suggestion: DeepReadonly<T> type
See original GitHub issueTypeScript Version: 2.1.1 / nightly (2.2.0-dev.201xxxxx)
Code
It would be nice to have a shard, standard library type that allows to express deep readonly-ness (not really const, since methods are out of scope, but still…):
interface Y { a: number; }
interface X { y: Y; }
let x: Readonly<X> = {y: {a: 1}};
x.y.a = 2; // Succeeds, which is expected, but it'd be nice to have a common way to express deep readonly
type DeepReadonly<T> = {
readonly [P in keyof T]: DeepReadonly<T[P]>;
}
let deepX: DeepReadonly<X> = {y: {a: 1}};
deepX.y.a = 2; // Fails as expected!
Issue Analytics
- State:
- Created 7 years ago
- Reactions:240
- Comments:51 (7 by maintainers)
Top Results From Across the Web
DeepReadonly Object Typescript - Stack Overflow
I modified the example slightly to use the type inference for the readonly array value type because I find (infer R)[] clearer than...
Read more >Are readonly interfaces possible? : r/typescript - Reddit
type DeepReadonly<T> = { readonly [Key in keyof T]: DeepReadonly<T[Key]>; } ... I would suggest against using readonly on anything but arrays.
Read more >`DeepReadonly` doesn't handle arrays properly - Issuehunt
Suggested solution(s). I was able to have to rule removed by changing T extends _DeepReadonlyArray<infer U> (https://github.com/piotrwitek/utility-types/blob ...
Read more >Microsoft/TypeScript - Gitter
where().NonBannedUsers();. and i know that i cannot use class generic type in static method, but this shows the idea. I tried numerous times...
Read more >Deep Readonly
Implement a generic DeepReadonly<T> which makes every parameter of an object and its ... type DeepReadonly<T> = { readonly [P in keyof T]:...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
With how complex these
DeepReadOnly
definitions are, it would be nice to see it provided directly by TypeScript.This is my implementation of
DeepReadonly
. I named itImmutable
so it doesn’t clash withReadonly
.It handles
ReadonlyArray
andReadonlyMap
. It also handlesFunction
types so their instances still can be called after being applied by this modifier.