Types: Add types for ReadonlyObservable, ReaonlyObservableArray, ReadonlyComputed #2476
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This adds types for representing immutable versions of observables, observable arrays, and computeds. The changes in this PR match changes that were introduced into the public typings in DefinitelyTyped/DefinitelyTyped#30499.
Although the underlying objects may actually be mutable, it's frequently useful to treat them as if they weren't: functions can accept readonly versions to indicate that they won't modify the contents, or things can be made publicly immutable, while still being privately mutable.
The consumer can read the value, subscribe to it, or call
incr
to increment it, but they can't set arbitrary values without circumventing the types.Additionally, while
Computed<T>
is no longer assignable toObservable<T>
like it was in the public typings (missing the '.willMutate' methods and the '.valueHasMutatedand
.valueWillMutatemethods), a computed is assignable to
ReadonlyObservable`, which is convenient for functions like:instead of:
In theory, certain overrides of
ko.computed
should return readonly computeds, not writable computeds:This PR does not address that issue. It never was addressed in the public typings - it caused a prohibitive number of type errors in our project, but it might be a smoother transition here. (A lot of the 'prohibitive errors' are type errors we're going to need to fix to go from 3.4 to 3.5 anyway)