aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorShinigami <[email protected]>2023-05-04 16:42:29 +0200
committerGitHub <[email protected]>2023-05-04 16:42:29 +0200
commit2e9ed960e3a11e4dcb78a434563fc04890c00c3d (patch)
tree566aa44b9bb085b8a42c6f211b7ea93af4d8408f
parent0740aa0da3b2ac1da4fd8a134d650162457552b4 (diff)
downloadfaker-2e9ed960e3a11e4dcb78a434563fc04890c00c3d.tar.xz
faker-2e9ed960e3a11e4dcb78a434563fc04890c00c3d.zip
chore: rename generics (#2046)
-rw-r--r--.eslintrc.js7
-rw-r--r--scripts/apidoc/utils.ts8
-rw-r--r--scripts/generateLocales.ts7
-rw-r--r--src/definitions/definitions.ts4
-rw-r--r--src/locale-proxy.ts16
-rw-r--r--src/modules/helpers/index.ts36
-rw-r--r--src/modules/helpers/unique.ts12
-rw-r--r--src/utils/types.ts18
-rw-r--r--test/all_functional.spec.ts4
-rw-r--r--test/scripts/apidoc/__snapshots__/signature.spec.ts.snap2
-rw-r--r--test/scripts/apidoc/signature.example.ts1
-rw-r--r--test/support/seededRuns.ts83
12 files changed, 102 insertions, 96 deletions
diff --git a/.eslintrc.js b/.eslintrc.js
index e0b62ede..6e223951 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -48,6 +48,13 @@ module.exports = defineConfig({
leadingUnderscore: 'forbid',
trailingUnderscore: 'forbid',
},
+ {
+ format: ['PascalCase'],
+ selector: ['typeParameter'],
+ prefix: ['T'],
+ leadingUnderscore: 'forbid',
+ trailingUnderscore: 'forbid',
+ },
],
'@typescript-eslint/no-inferrable-types': [
'error',
diff --git a/scripts/apidoc/utils.ts b/scripts/apidoc/utils.ts
index 8a002f49..4f8d3440 100644
--- a/scripts/apidoc/utils.ts
+++ b/scripts/apidoc/utils.ts
@@ -47,10 +47,10 @@ export function adjustUrls(description: string): string {
return description.replace(/https:\/\/(next.)?fakerjs.dev\//g, '/');
}
-export function mapByName<T extends { name: string }, V>(
- input: T[],
- valueExtractor: (item: T) => V
-): Record<string, V> {
+export function mapByName<TInput extends { name: string }, TValue>(
+ input: TInput[],
+ valueExtractor: (item: TInput) => TValue
+): Record<string, TValue> {
return input.reduce(
(acc, item) => ({ ...acc, [item.name]: valueExtractor(item) }),
{}
diff --git a/scripts/generateLocales.ts b/scripts/generateLocales.ts
index 591b6810..b1c4db0e 100644
--- a/scripts/generateLocales.ts
+++ b/scripts/generateLocales.ts
@@ -40,9 +40,10 @@ const pathDocsGuideLocalization = resolve(
);
// Workaround for nameOf<T>
-type PascalCase<S extends string> = S extends `${infer P1}_${infer P2}`
- ? `${Capitalize<P1>}${PascalCase<P2>}`
- : Capitalize<S>;
+type PascalCase<TName extends string> =
+ TName extends `${infer Prefix}_${infer Remainder}`
+ ? `${Capitalize<Prefix>}${PascalCase<Remainder>}`
+ : Capitalize<TName>;
type DefinitionType = {
[key in keyof LocaleDefinition]-?: PascalCase<`${key}Definition`>;
diff --git a/src/definitions/definitions.ts b/src/definitions/definitions.ts
index 30f965c3..ca495e34 100644
--- a/src/definitions/definitions.ts
+++ b/src/definitions/definitions.ts
@@ -22,8 +22,8 @@ import type { WordDefinition } from './word';
/**
* Wrapper type for all definition categories that will make all properties optional and allow extra properties.
*/
-export type LocaleEntry<T extends Record<string, unknown>> = {
- [P in keyof T]?: T[P] | null;
+export type LocaleEntry<TCategoryDefinition extends Record<string, unknown>> = {
+ [P in keyof TCategoryDefinition]?: TCategoryDefinition[P] | null;
} & Record<string, unknown>; // Unsupported & custom entries
/**
diff --git a/src/locale-proxy.ts b/src/locale-proxy.ts
index a4dcc018..47b371d6 100644
--- a/src/locale-proxy.ts
+++ b/src/locale-proxy.ts
@@ -61,21 +61,21 @@ export function createLocaleProxy(locale: LocaleDefinition): LocaleProxy {
* @param categoryData The module to create the proxy for.
*/
function createCategoryProxy<
- CategoryData extends Record<string | symbol, unknown>
+ TCategoryData extends Record<string | symbol, unknown>
>(
categoryName: string,
- categoryData: CategoryData = {} as CategoryData
-): Required<CategoryData> {
+ categoryData: TCategoryData = {} as TCategoryData
+): Required<TCategoryData> {
return new Proxy(categoryData, {
- has(target: CategoryData, entryName: keyof CategoryData): boolean {
+ has(target: TCategoryData, entryName: keyof TCategoryData): boolean {
const value = target[entryName];
return value != null;
},
get(
- target: CategoryData,
- entryName: keyof CategoryData
- ): CategoryData[keyof CategoryData] {
+ target: TCategoryData,
+ entryName: keyof TCategoryData
+ ): TCategoryData[keyof TCategoryData] {
const value = target[entryName];
if (typeof entryName === 'symbol' || entryName === 'nodeType') {
return value;
@@ -97,5 +97,5 @@ function createCategoryProxy<
set: throwReadOnlyError,
deleteProperty: throwReadOnlyError,
- }) as Required<CategoryData>;
+ }) as Required<TCategoryData>;
}
diff --git a/src/modules/helpers/index.ts b/src/modules/helpers/index.ts
index e6cf9075..3db15ca4 100644
--- a/src/modules/helpers/index.ts
+++ b/src/modules/helpers/index.ts
@@ -732,7 +732,7 @@ export class HelpersModule {
/**
* Returns the result of the callback if the probability check was successful, otherwise `undefined`.
*
- * @template T The type of result of the given callback.
+ * @template TResult The type of result of the given callback.
*
* @param callback The callback to that will be invoked if the probability check was successful.
* @param options The options to use. Defaults to `{}`.
@@ -745,8 +745,8 @@ export class HelpersModule {
*
* @since 6.3.0
*/
- maybe<T>(
- callback: () => T,
+ maybe<TResult>(
+ callback: () => TResult,
options: {
/**
* The probability (`[0.00, 1.00]`) of the callback being invoked.
@@ -755,7 +755,7 @@ export class HelpersModule {
*/
probability?: number;
} = {}
- ): T | undefined {
+ ): TResult | undefined {
if (this.faker.datatype.boolean(options)) {
return callback();
}
@@ -990,7 +990,7 @@ export class HelpersModule {
*
* This does the same as `objectValue` except that it ignores (the values assigned to) the numeric keys added for TypeScript enums.
*
- * @template EnumType Type of generic enums, automatically inferred by TypeScript.
+ * @template T Type of generic enums, automatically inferred by TypeScript.
*
* @param enumObject Enum to pick the value from.
*
@@ -1006,11 +1006,11 @@ export class HelpersModule {
*
* @since 8.0.0
*/
- enumValue<EnumType extends Record<string | number, string | number>>(
- enumObject: EnumType
- ): EnumType[keyof EnumType] {
+ enumValue<T extends Record<string | number, string | number>>(
+ enumObject: T
+ ): T[keyof T] {
// ignore numeric keys added by TypeScript
- const keys: Array<keyof EnumType> = Object.keys(enumObject).filter((key) =>
+ const keys: Array<keyof T> = Object.keys(enumObject).filter((key) =>
isNaN(Number(key))
);
const randomKey = this.arrayElement(keys);
@@ -1280,7 +1280,7 @@ export class HelpersModule {
* Generates a unique result using the results of the given method.
* Used unique entries will be stored internally and filtered from subsequent calls.
*
- * @template Method The type of the method to execute.
+ * @template TMethod The type of the method to execute.
*
* @param method The method used to generate the values.
* @param args The arguments used to call the method.
@@ -1304,14 +1304,14 @@ export class HelpersModule {
* More info can be found in issue [faker-js/faker #1785](https://github.com/faker-js/faker/issues/1785).
*/
unique<
- Method extends (
+ TMethod extends (
// TODO @Shinigami92 2023-02-14: This `any` type can be fixed by anyone if they want to.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...parameters: any[]
) => RecordKey
>(
- method: Method,
- args: Parameters<Method> = [] as Parameters<Method>,
+ method: TMethod,
+ args: Parameters<TMethod> = [] as Parameters<TMethod>,
options: {
/**
* This parameter does nothing.
@@ -1358,7 +1358,7 @@ export class HelpersModule {
*/
store?: Record<RecordKey, RecordKey>;
} = {}
- ): ReturnType<Method> {
+ ): ReturnType<TMethod> {
deprecated({
deprecated: 'faker.helpers.unique',
proposed:
@@ -1387,7 +1387,7 @@ export class HelpersModule {
/**
* Generates an array containing values returned by the given method.
*
- * @template T The type of elements.
+ * @template TResult The type of elements.
*
* @param method The method used to generate the values.
* @param options The optional options object.
@@ -1399,8 +1399,8 @@ export class HelpersModule {
*
* @since 8.0.0
*/
- multiple<T>(
- method: () => T,
+ multiple<TResult>(
+ method: () => TResult,
options: {
/**
* The number or range of elements to generate.
@@ -1420,7 +1420,7 @@ export class HelpersModule {
max: number;
};
} = {}
- ): T[] {
+ ): TResult[] {
const count = this.rangeToNumber(options.count ?? 3);
if (count <= 0) {
return [];
diff --git a/src/modules/helpers/unique.ts b/src/modules/helpers/unique.ts
index 90896c64..d6bede7a 100644
--- a/src/modules/helpers/unique.ts
+++ b/src/modules/helpers/unique.ts
@@ -57,7 +57,7 @@ Try adjusting maxTime or maxRetries parameters for faker.helpers.unique().`
* Generates a unique result using the results of the given method.
* Used unique entries will be stored internally and filtered from subsequent calls.
*
- * @template Method The type of the method to execute.
+ * @template TMethod The type of the method to execute.
*
* @param method The method used to generate the values.
* @param args The arguments used to call the method.
@@ -71,14 +71,14 @@ Try adjusting maxTime or maxRetries parameters for faker.helpers.unique().`
* @param options.store The store of unique entries. Defaults to `GLOBAL_UNIQUE_STORE`.
*/
export function exec<
- Method extends (
+ TMethod extends (
// TODO @Shinigami92 2023-02-14: This `any` type can be fixed by anyone if they want to.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...parameters: any[]
) => RecordKey
>(
- method: Method,
- args: Parameters<Method>,
+ method: TMethod,
+ args: Parameters<TMethod>,
options: {
startTime?: number;
maxTime?: number;
@@ -88,7 +88,7 @@ export function exec<
compare?: (obj: Record<RecordKey, RecordKey>, key: RecordKey) => 0 | -1;
store?: Record<RecordKey, RecordKey>;
} = {}
-): ReturnType<Method> {
+): ReturnType<TMethod> {
const now = new Date().getTime();
const {
@@ -132,7 +132,7 @@ export function exec<
}
// Execute the provided method to find a potential satisfied value.
- const result: ReturnType<Method> = method(...args) as ReturnType<Method>;
+ const result: ReturnType<TMethod> = method(...args) as ReturnType<TMethod>;
// If the result has not been previously found, add it to the found array and return the value as it's unique.
if (compare(store, result) === -1 && exclude.indexOf(result) === -1) {
diff --git a/src/utils/types.ts b/src/utils/types.ts
index 8c1bfe6b..c7aaf86c 100644
--- a/src/utils/types.ts
+++ b/src/utils/types.ts
@@ -3,9 +3,9 @@
*
* @see https://github.com/microsoft/TypeScript/issues/29729#issuecomment-471566609
*/
-export type LiteralUnion<T extends U, U = string> =
- | T
- | (U & { zz_IGNORE_ME?: never });
+export type LiteralUnion<TSuggested extends TBase, TBase = string> =
+ | TSuggested
+ | (TBase & { zz_IGNORE_ME?: never });
/**
* A function that returns a value.
@@ -22,18 +22,18 @@ export type Callable = (
/**
* Type that represents a single method/function name of the given type.
*/
-export type MethodOf<ObjectType, Signature extends Callable = Callable> = {
- [Key in keyof ObjectType]: ObjectType[Key] extends Signature
+export type MethodOf<TObjectType, TSignature extends Callable = Callable> = {
+ [Key in keyof TObjectType]: TObjectType[Key] extends TSignature
? Key extends string
? Key
: never
: never;
-}[keyof ObjectType];
+}[keyof TObjectType];
/**
* Type that represents all method/function names of the given type.
*/
export type MethodsOf<
- ObjectType,
- Signature extends Callable = Callable
-> = ReadonlyArray<MethodOf<ObjectType, Signature>>;
+ TObjectType,
+ TSignature extends Callable = Callable
+> = ReadonlyArray<MethodOf<TObjectType, TSignature>>;
diff --git a/test/all_functional.spec.ts b/test/all_functional.spec.ts
index 2035f32e..f18e5fec 100644
--- a/test/all_functional.spec.ts
+++ b/test/all_functional.spec.ts
@@ -18,8 +18,8 @@ function isMethodOf(mod: string) {
return (meth: string) => typeof fakerEN[mod][meth] === 'function';
}
-type SkipConfig<Module> = Partial<
- Record<keyof Module, '*' | ReadonlyArray<keyof typeof allLocales>>
+type SkipConfig<TModule> = Partial<
+ Record<keyof TModule, '*' | ReadonlyArray<keyof typeof allLocales>>
>;
const BROKEN_LOCALE_METHODS = {
diff --git a/test/scripts/apidoc/__snapshots__/signature.spec.ts.snap b/test/scripts/apidoc/__snapshots__/signature.spec.ts.snap
index 15bb4d00..525b676c 100644
--- a/test/scripts/apidoc/__snapshots__/signature.spec.ts.snap
+++ b/test/scripts/apidoc/__snapshots__/signature.spec.ts.snap
@@ -43,7 +43,7 @@ exports[`signature > analyzeSignature() > complexArrayParameter 1`] = `
"returns": "T",
"seeAlsos": [],
"since": "",
- "sourcePath": "test/scripts/apidoc/signature.example.ts#L356",
+ "sourcePath": "test/scripts/apidoc/signature.example.ts#L357",
"throws": undefined,
}
`;
diff --git a/test/scripts/apidoc/signature.example.ts b/test/scripts/apidoc/signature.example.ts
index 6bb835c1..5d557a3f 100644
--- a/test/scripts/apidoc/signature.example.ts
+++ b/test/scripts/apidoc/signature.example.ts
@@ -349,6 +349,7 @@ export class SignatureTest {
* Complex array parameter.
*
* @template T The type of the entries to pick from.
+ *
* @param array Array to pick the value from.
* @param array[].weight The weight of the value.
* @param array[].value The value to pick.
diff --git a/test/support/seededRuns.ts b/test/support/seededRuns.ts
index 5926fb5c..74db7208 100644
--- a/test/support/seededRuns.ts
+++ b/test/support/seededRuns.ts
@@ -30,15 +30,15 @@ type OnlyMethodsFaker = {
/**
* The type allowing only the names of methods that have exactly zero arguments.
*/
-type NoArgsMethodOf<ObjectType> = MethodOf<ObjectType> &
+type NoArgsMethodOf<TObjectType> = MethodOf<TObjectType> &
{
- [Key in MethodOf<ObjectType, () => unknown>]: ObjectType[Key] extends (
+ [Key in MethodOf<TObjectType, () => unknown>]: TObjectType[Key] extends (
arg0: string | number | boolean | Record<string, undefined>,
...args: unknown[]
) => unknown
? Key
: never;
- }[MethodOf<ObjectType, () => unknown>];
+ }[MethodOf<TObjectType, () => unknown>];
/**
* Method that prepares seeded tests.
@@ -68,19 +68,16 @@ type NoArgsMethodOf<ObjectType> = MethodOf<ObjectType> &
* })
*/
export function seededTests<
- K extends FakerModule,
- M extends Record<string, Callable> = OnlyMethodsFaker[K]
+ TFakerModule extends FakerModule,
+ TModule extends Record<string, Callable> = OnlyMethodsFaker[TFakerModule]
>(
faker: Faker,
- module: K,
- factory: (tg: TestGenerator<K, M>, setup: () => void) => void
+ module: TFakerModule,
+ factory: (tg: TestGenerator<TFakerModule, TModule>, setup: () => void) => void
): void {
describe.each(seededRuns)('%s', (seed) => {
- const testGenerator: TestGenerator<K, M> = new TestGenerator(
- faker,
- seed,
- module
- );
+ const testGenerator: TestGenerator<TFakerModule, TModule> =
+ new TestGenerator(faker, seed, module);
factory(testGenerator, () => testGenerator.setup());
testGenerator.expectAllMethodsToBeTested();
@@ -93,18 +90,18 @@ export function seededTests<
* The individual methods generate default test blocks, that use test snapshots to verify consistent return values.
*/
class TestGenerator<
- ModuleName extends FakerModule,
- Module extends Record<string, Callable> = OnlyMethodsFaker[ModuleName]
+ TModuleName extends FakerModule,
+ TModule extends Record<string, Callable> = OnlyMethodsFaker[TModuleName]
> {
- private readonly tested: Set<MethodOf<Module>> = new Set();
- private readonly module: Module;
+ private readonly tested: Set<MethodOf<TModule>> = new Set();
+ private readonly module: TModule;
constructor(
private readonly faker: Faker,
private readonly seed: number,
- private readonly moduleName: ModuleName
+ private readonly moduleName: TModuleName
) {
- this.module = this.faker[moduleName] as unknown as Module;
+ this.module = this.faker[moduleName] as unknown as TModule;
}
/**
@@ -112,7 +109,7 @@ class TestGenerator<
*
* @param method The method name to check.
*/
- private expectNotTested(method: MethodOf<Module>): void {
+ private expectNotTested(method: MethodOf<TModule>): void {
expect(
this.tested.has(method),
`${method} not to be tested yet`
@@ -139,9 +136,9 @@ class TestGenerator<
* @param args The arguments to call it with.
* @param repetitions The number of times to call it.
*/
- private callAndVerify<MethodName extends MethodOf<Module>>(
- method: MethodName,
- args: Parameters<Module[MethodName]>,
+ private callAndVerify<TMethodName extends MethodOf<TModule>>(
+ method: TMethodName,
+ args: Parameters<TModule[TMethodName]>,
repetitions: number = 1
): void {
this.setup();
@@ -157,7 +154,7 @@ class TestGenerator<
*
* @param method The name of the method.
*/
- skip(method: MethodOf<Module>): this {
+ skip(method: MethodOf<TModule>): this {
this.expectNotTested(method);
vi_it.skip(method);
return this;
@@ -170,7 +167,7 @@ class TestGenerator<
*
* @deprecated Implement a proper test.
*/
- todo(method: MethodOf<Module>): this {
+ todo(method: MethodOf<TModule>): this {
this.expectNotTested(method);
vi_it.todo(method);
return this;
@@ -181,7 +178,7 @@ class TestGenerator<
*
* @param method The name of the method.
*/
- it<MethodName extends NoArgsMethodOf<Module>>(method: MethodName): this {
+ it<TMethodName extends NoArgsMethodOf<TModule>>(method: TMethodName): this {
return this.itRepeated(method, 1);
}
@@ -192,15 +189,15 @@ class TestGenerator<
* @param method The name of the method.
* @param repetitions The number of repetitions to run.
*/
- itRepeated<MethodName extends NoArgsMethodOf<Module>>(
- method: MethodName,
+ itRepeated<TMethodName extends NoArgsMethodOf<TModule>>(
+ method: TMethodName,
repetitions: number
): this {
this.expectNotTested(method);
vi_it(method, () =>
this.callAndVerify(
method,
- [] as unknown as Parameters<Module[MethodName]>,
+ [] as unknown as Parameters<TModule[TMethodName]>,
repetitions
)
);
@@ -212,8 +209,8 @@ class TestGenerator<
*
* @param methods The names of the methods.
*/
- itEach<MethodName extends NoArgsMethodOf<Module>>(
- ...methods: MethodName[]
+ itEach<TMethodName extends NoArgsMethodOf<TModule>>(
+ ...methods: TMethodName[]
): this {
for (const method of methods) {
this.it(method);
@@ -229,12 +226,12 @@ class TestGenerator<
* @param method The name of the method.
* @param factory The factory used to generate the individual tests.
*/
- describe<MethodName extends MethodOf<Module>>(
- method: MethodName,
- factory: (tester: MethodTester<Module[MethodName]>) => void
+ describe<TMethodName extends MethodOf<TModule>>(
+ method: TMethodName,
+ factory: (tester: MethodTester<TModule[TMethodName]>) => void
): this {
this.expectNotTested(method);
- const callAndVerify: TestGenerator<ModuleName, Module>['callAndVerify'] =
+ const callAndVerify: TestGenerator<TModuleName, TModule>['callAndVerify'] =
this.callAndVerify.bind(this);
const variantNames = new Set<string>();
const expectVariantNotTested = (name: string): void => {
@@ -245,8 +242,8 @@ class TestGenerator<
variantNames.add(name);
};
- const tester: MethodTester<Module[MethodName]> = {
- it(name: string, ...args: Parameters<Module[MethodName]>) {
+ const tester: MethodTester<TModule[TMethodName]> = {
+ it(name: string, ...args: Parameters<TModule[TMethodName]>) {
expectVariantNotTested(name);
vi_it(name, () => callAndVerify(method, args));
return tester;
@@ -254,7 +251,7 @@ class TestGenerator<
itRepeated(
name: string,
repetitions: number,
- ...args: Parameters<Module[MethodName]>
+ ...args: Parameters<TModule[TMethodName]>
) {
expectVariantNotTested(name);
vi_it(name, () => callAndVerify(method, args, repetitions));
@@ -273,9 +270,9 @@ class TestGenerator<
*
* @param methods The names of the methods to generate the tests for.
*/
- describeEach<MethodName extends MethodOf<Module>>(
- ...methods: MethodName[]
- ): (factory: (tester: MethodTester<Module[MethodName]>) => void) => this {
+ describeEach<TMethodName extends MethodOf<TModule>>(
+ ...methods: TMethodName[]
+ ): (factory: (tester: MethodTester<TModule[TMethodName]>) => void) => this {
return (factory) => {
for (const method of methods) {
this.describe(method, factory);
@@ -306,14 +303,14 @@ class TestGenerator<
/**
* Simple interface for a test generator for a given method.
*/
-interface MethodTester<Method extends Callable> {
+interface MethodTester<TMethod extends Callable> {
/**
* Generates a test for the method.
*
* @param name The name of the test case.
* @param args The arguments to use in the test.
*/
- it(name: string, ...args: Parameters<Method>): this;
+ it(name: string, ...args: Parameters<TMethod>): this;
/**
* Generates a repeated test for the method.
@@ -326,6 +323,6 @@ interface MethodTester<Method extends Callable> {
itRepeated(
name: string,
repetitions: number,
- ...args: Parameters<Method>
+ ...args: Parameters<TMethod>
): this;
}