LoginSignup
0

More than 5 years have passed since last update.

Ngrxを学習する上で必要なTypescriptの学習

Posted at

はじめに

NgRxはAngularの状態管理ライブラリです。普段では見えてないtypescriptの使い方があったので、解説しようと思います・

Reducer, Selector, Entity

定義したインターフェースに、値をオブジェクトリテラルのまま代入することができます

参考
https://github.com/typescript-exercise/typescript-exercise.github.io/wiki/%E6%96%87%E6%B3%95%EF%BC%93%E3%80%80%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E5%9E%8B%E3%83%AA%E3%83%86%E3%83%A9%E3%83%AB

簡単な例

{
    str : string;
    num : number;
} = {
    str: 'text',
    num: 10,
    bool: true // 余分なプロパティはエラーにならない
};

使用例

entityの特有のインターフェースをもったadpterのgetSelectorsメソッドによって、EntitiySelectorsを返します。

getSelectors(): EntitySelectors<T, EntityState<T>>;
export interface EntitySelectors<T, V> {
    selectIds: (state: V) => string[] | number[];
    selectEntities: (state: V) => Dictionary<T>;
    selectAll: (state: V) => T[];
    selectTotal: (state: V) => number;
}

特有のインターフェースを持った、 selectIds, selectEntities, selectAll, selectTotal を作ります。

export const {
  selectIds,
  selectEntities,
  selectAll,
  selectTotal,
} = adapter.getSelectors();

Selector

Selectorでは、ファクトリ関数(1つのオブジェクトを返す関数)を使います。

参考
https://www.webprofessional.jp/factory-functions-javascript/

簡単な例

creJelly()によって、オブジェクトを返しています。

function creJelly() {
  return {
    type: 'jelly',
    colour: 'red'
    scoops: 3
  };
}

使用例

export const getProjects = createSelector(
    getProjectState,
    fromProject.selectAll
);

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0