cartant/ts-action

How to use TypeScript classes instead of plain Objects

st-clair-clarke opened this issue · 3 comments

Hi. Congrats on a very interesting offering. I currently use typescript-fsa.

I was looking for an example that use Typescript classes as data for storage in the store but could not find one. If one exist please show me a link. If none, exist, how would I create a payload example with the following TypeScript classes and interface:

export interface IPhone {
type: string
provider: string
number: string
}

export class Phone {
type: string = ''
provider: string = ''
number: string = ''
}

My attempt below does not work

import { IPhone, Phone } from 'phone.model'
import { action, payload, union } from 'ts-action'

export const AddPatientPhoneData = action('[Patient Phone] ADD_DATA', payload<{phone: IPhone}>());

const All = union(AddPatientPhoneData)

export function addPatientPhoneDataReducerr(state: IPhone = new Phone(), action: typeof All): IPhone{
  
  switch (action.type){
    case AddPatientPhoneData.type:
      return {...state, phone: action.phone} //phone and action.phone show errors
  }
}

How would I go about creating and Add, Update and Delete action having a payload and the creation of its store reducer example?

Thanks.

If you've delcared an action creator like this:

export const AddPatientPhoneData = action(
  '[Patient Phone] ADD_DATA',
  payload<{ phone: IPhone }>()
);

The effected actions will have this shape:

{
    type: "[Patient Phone] ADD_DATA";
    payload: {
        phone: {
            type: string;
            provider: string;
            number: string;
        }
    }
}

So your reducer would need to use the payload property:

return { ...state, phone: action.payload.phone };

If you don't want the a payload property in the effected actions, use the props method instead of the payload method when declaring the action creator.

I have tried your suggestion, but I am still getting the error Type'{phone: any; type: string; provider: string; number: string:}' is not assignable to type 'IPhone'. Object literal may only specify know properties, and 'phone' does not exist.

This has nothing to do with ts-action. I misread the code in your snippet. The error explains the situation. Your state has the shape of IPhone which has no phone property. It's as simple as that.

You need to decide what you are doing with your state. Maybe you want something like this?

return { ...state, ...action.payload.phone };