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

fix: exclude class instance from DeepSignal #4605

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions modules/signals/spec/types/signal-state.types.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,22 @@ describe('signalState', () => {
);
});

it('does not create deep signals for a class instance', () => {
const snippet = `
class User {
id = 0;
name = 'Konrad';
}

const state = signalState({ user: new User() });
const user = state.user;
`;

expectSnippet(snippet).toSucceed();

expectSnippet(snippet).toInfer('user', 'Signal<User>');
});

it('does not create deep signals for optional state slices', () => {
const snippet = `
type State = {
Expand Down
33 changes: 32 additions & 1 deletion modules/signals/src/ts-helpers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { Signal } from '@angular/core';
import { signalState } from './signal-state';

export type Prettify<T> = { [K in keyof T]: T[K] } & {};

export type IsRecord<T> = T extends object
Expand All @@ -9,7 +12,11 @@ export type IsRecord<T> = T extends object
? false
: T extends Function
? false
: true
: T extends { prototype: unknown } // check for constructor did not work
? false
: T extends { [key: string]: unknown }
? true
: false
: false;

export type IsUnknownRecord<T> = string extends keyof T
Expand All @@ -27,3 +34,27 @@ export type IsKnownRecord<T> = IsRecord<T> extends true
export type OmitPrivate<T> = {
[K in keyof T as K extends `_${string}` ? never : K]: T[K];
};

class User {
id = 0;
name = 'Konrad';
}

const state = {
user: new User(),
id: 1,
address: { city: 'Wien', zip: '1040' },
};

type AssertFalse<T extends false> = T;
type AssertTrue<T extends true> = T;

type T1 = AssertFalse<IsRecord<User>>;
type T2 = AssertFalse<IsRecord<typeof state.id>>;
type T3 = AssertTrue<IsRecord<typeof state.address>>;

const store = signalState(state);
const address: Signal<{ city: string; zip: string }> = store.address;
const user: Signal<User> = store.user;
const zip: Signal<string> = store.address.zip;
const id: Signal<number> = store.id;
Loading