Search code examples
typescriptjavascript-objectsdefault-valuetyping

How to merge an interface and default values of a variable?


I have the disgusting code below where I want to combine the safety of TypeScript typing and default values of a variable:

interface Store {
  infinoteToken: string | null,
  allNotes: Note[],
  // plenty more
}

export const store: Store = reactive({
  infinoteToken: null,
  allNotes: [],
  // plenty more
})

I end up with two blocks of code with duplicated information.

Is there a way to combine these two elements to declare an Object with default values and types for its members?


Solution

  • This all can be moved to a class with default implementation:

    class Store {
      infinoteToken: string | null = null;
      allNotes: Note[] = [];
      // plenty more
    
    }
    
    export const store = reactive(new Store());