Home > Software design >  Should i have separate types for the same data?
Should i have separate types for the same data?

Time:10-19

I'm creating my first react-native app with firebase / redux toolkit / typescript and I'm stuck on some points.

Atm I have this type

type Program = {
  id?: string
  name: string!
  trainings: Record<string, Training>
  userId: string
}

On my redux state I have this

export interface ProgramState {
  programs: Program[]
  currentEditingProgram: Program | null
  loading: boolean
}

const initialState: ProgramState = {
  programs: [],
  currentEditingProgram: null,
  loading: true,
}

My problem is that when i update with this function ...

export const updateProgramById = createAsyncThunk(
  "programs/updateById",
  async (program: Program, thunkAPI) => {
      await updateDoc(doc(db, programsCol.id, program.id!), program)
  }

... i need to remove id property from {program} to save it on firestore as :

{id}:{
name:"",
trainings:[]
userId:""

AND NOT 

{id}:{
id:"",//Same as {id}
name:"",
trainings:[]
userId:""

My questions are :

  1. Should i have separate type, one with id one without ?
  2. When I want to update one Program, should i save my currentEditingProgram object or just the id (I have a screen ProgramDetail and i can navigate to Training screen details)

CodePudding user response:

You can have a separate type holding only data, without ID, and a generic type that combines those like this:

Typescript playgorund

//generic redux type with ID
type ReduxIdItem<T, IdType = string> = { id: IdType, data: T }

type ProgramData = {
  name: string
  trainings: Record<string, Training>
  userId: string
}

type ProgramRedux = ReduxIdItem<ProgramData>;

const test: ProgramRedux = {} as ProgramRedux;

//now you have the object separated from the id

test.data //hods the data without id
test.id // holds the id
  • Related