0

如何将data属性隐式传递给new MockBuilderin .withArrayObject('data', 6, () => new MockBuilder()

我不想在嵌套中分配类型new MockBuilder

type Model = {
  data: {
    abc: string;
    qwe: string;
  }[];
};

type BaseType = string | number | boolean | Date | unknown;
type MockType<T> = Record<
  keyof T,
  | BaseType
  | BaseType[]
  | Record<string, BaseType | BaseType[]>
  | Record<string, BaseType | BaseType[]>[]
>;
export class MockBuilder<T> {
  private mock = {} as MockType<T>;
  private static randomString(
    length: number,
    chars = 'abcdefghijklmnopqrstuvwxyz',
  ) {
    let result = '';
    for (let i = length; i > 0; i -= 1)
      result += chars[Math.round(Math.random() * (chars.length - 1))];
    return result;
  }
  private static getRandomFromArray<A>(array: Array<A>) {
    return array[Math.floor(Math.random() * array.length)];
  }
  private static fillFieldString(fieldContent?: Array<string>) {
    return fieldContent === undefined
      ? MockBuilder.randomString(16)
      : MockBuilder.getRandomFromArray(fieldContent);
  }
  withString(fieldName: keyof T, fieldContent?: Array<string>): MockBuilder<T> {
    this.mock[fieldName] = MockBuilder.fillFieldString(fieldContent);
    return this;
  }
  withArrayObject<
    K extends keyof T,
    E extends T[K] extends (infer U)[] ? U : never
  >(
    fieldName: K,
    length: number,
    fieldContent: () => MockBuilder<E>,
  ): MockBuilder<T> {
    this.mock[fieldName] = Array(length)
      .fill(1)
      .map(() => fieldContent().build());
    return this;
  }
  build() {
    return this.mock as T;
  }
}

const mockResponse = new MockBuilder<Model>() //
  .withArrayObject('data', 6, () =>
    new MockBuilder()
      .withString('abc')
      .withString('qwe'),
  );

操场

4

0 回答 0