Skip to content

Commit 6c92d65

Browse files
alxhubpkozlowski-opensource
authored andcommitted
fix(core): add hasValue narrowing to ResourceRef (#59708)
`hasValue` attempts to narrow the type of a resource to exclude `undefined`. Because of the way signal types merge in TS, this only works if the type of the resource is the same general type as `hasValue` asserts. For example, if `res` is `WritableResource<string|undefined>` then `.hasValue()` correctly asserts that `res` is `WritableResource<string>` and `.value()` will be narrowed. If `res` is `ResourceRef<string|undefined>` then that narrowing does _not_ work correctly, since `.hasValue()` will assert `res` is `WritableResource<string>` and TS will combine that for a final type of `ResourceRef<string|undefined> & WritableResource<string>`. The final type of `.value()` then will not narrow. This commit fixes the above problem by adding a `.hasValue()` override to `ResourceRef` which asserts the resource is of type `ResourceRef`. Fixes #59707 PR Close #59708
1 parent 127fc0d commit 6c92d65

File tree

3 files changed

+5
-1
lines changed

3 files changed

+5
-1
lines changed

goldens/public-api/core/index.api.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1634,6 +1634,8 @@ export type ResourceOptions<T, R> = PromiseResourceOptions<T, R> | StreamingReso
16341634
// @public
16351635
export interface ResourceRef<T> extends WritableResource<T> {
16361636
destroy(): void;
1637+
// (undocumented)
1638+
hasValue(): this is ResourceRef<Exclude<T, undefined>>;
16371639
}
16381640

16391641
// @public

packages/core/src/resource/api.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,8 @@ export interface WritableResource<T> extends Resource<T> {
133133
* @experimental
134134
*/
135135
export interface ResourceRef<T> extends WritableResource<T> {
136+
hasValue(): this is ResourceRef<Exclude<T, undefined>>;
137+
136138
/**
137139
* Manually destroy the resource, which cancels pending requests and returns it to `idle` state.
138140
*/

packages/core/src/resource/resource.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ abstract class BaseWritableResource<T> implements WritableResource<T> {
103103
() => this.status() === ResourceStatus.Loading || this.status() === ResourceStatus.Reloading,
104104
);
105105

106-
hasValue(): this is WritableResource<Exclude<T, undefined>> {
106+
hasValue(): this is ResourceRef<Exclude<T, undefined>> {
107107
return this.value() !== undefined;
108108
}
109109

0 commit comments

Comments
 (0)