简体   繁体   中英

what's the best way to type a mock store?

Our test code is riddled with code like this in our tests...

const mockState = {
      client: {
        users: {
          results: {
            something: -91893.21,
          },
        },
      },
    };

Obviously mockState is untyped. I can't type it as RootState since that interface has heaps of properties that this test doesn't need.

I looked at Partial and DeepPartial but they don't really help since any json would implement any DeepPartial since every property would be optional. Is there a way to type a json object so that all it's properties match a specific type, but not all properties are required. Confusing question. I want to type mockState to IWhatever so that it won't compile unless IWhatever has a property called client, which has a property called users etc.

If you do the assignment at the same time as you do the variable definitionobject freshness kicks in and will prevent you from adding any additional properties.

Example

type RootState = {
  client: {
    a: {
      something: number
    },
    b: {
      something: number
    }
  },
  server: {
    a: {
      something: number
    },
    b: {
      something: number
    }
  }
}

// Reference DeepPartial
type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends Array<infer U>
    ? Array<DeepPartial<U>>
    : T[P] extends ReadonlyArray<infer U>
      ? ReadonlyArray<DeepPartial<U>>
      : DeepPartial<T[P]>
};


// Okay 
const mockState: DeepPartial<RootState> = {
  client: {
    a: {
      something: 123
    }
  }
}

// Not Okay 
const mockStateBad: DeepPartial<RootState> = {
  client: {
    a: {
      somethings: 123 // ERROR 
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM