Skip to content

NGRX Entity, Stronger Typing on getInitialState #4422

@GavynHolt

Description

@GavynHolt

Which @ngrx/* package(s) are relevant/related to the feature request?

entity

Information

Hi NGRX Team,

When using NGRX Entity package and setting the initial state, unfortunately it is possible to introduce unknown properties.

I'd like to show briefly how I am solving this and ask if it's possible for you to implement this somehow for all to enjoy? Thanks in advance:

Firstly, in my reducers, consider this simplified initial Entity State, with an irrelevant entity type of "ExampleEntity":

export interface State extends EntityState<ExampleEntity> {
  selectedId?: string;
  loaded: boolean;
  error?: HttpErrorResponse;
  searchText: string;
}

when calling

myAdapter.getInitialState({ 
  loaded: false,
  searchText: '',
  unkownProperty: "test" <--- This does NOT throw an error as I expect (since it is not a part of ExampleEntity)
})

as recommended in the documentation, unfortunately it is possible to introduce unknown properties without any error, such as the "unkownProperty" shown above.

To resolve this, I have type casted typing of getInitialState:

export const initialState: State = myAdapter.getInitialState<Omit<State, keyof EntityState<ExampleEntity>>>({
  loaded: false,
  searchText: '',
  unkownProperty: "test" <--- This will now throw an error
});

If you have the time, perhaps you could introduce some more strict typing similar to the above to allow for IDE's to catch these sorts of errors without casting? Thanks very much for your time.

Describe any alternatives/workarounds you're currently using

export const initialState: State = myAdapter.getInitialState<Omit<State, keyof EntityState<ExampleEntity>>>({
  loaded: false,
  searchText: '',
  unkownProperty: "test" <--- This will now throw an error
});

Using TypeScript's "Omit" as shown above allows for this to work.

I would be willing to submit a PR to fix this issue

  • Yes
  • No

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions