Skip to content

Commit

Permalink
chore: rename generics (#2046)
Browse files Browse the repository at this point in the history
  • Loading branch information
Shinigami92 committed May 4, 2023
1 parent 0740aa0 commit 2e9ed96
Show file tree
Hide file tree
Showing 12 changed files with 102 additions and 96 deletions.
7 changes: 7 additions & 0 deletions .eslintrc.js
Expand Up @@ -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',
Expand Down
8 changes: 4 additions & 4 deletions scripts/apidoc/utils.ts
Expand Up @@ -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) }),
{}
Expand Down
7 changes: 4 additions & 3 deletions scripts/generateLocales.ts
Expand Up @@ -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`>;
Expand Down
4 changes: 2 additions & 2 deletions src/definitions/definitions.ts
Expand Up @@ -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

/**
Expand Down
16 changes: 8 additions & 8 deletions src/locale-proxy.ts
Expand Up @@ -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;
Expand All @@ -97,5 +97,5 @@ function createCategoryProxy<

set: throwReadOnlyError,
deleteProperty: throwReadOnlyError,
}) as Required<CategoryData>;
}) as Required<TCategoryData>;
}
36 changes: 18 additions & 18 deletions src/modules/helpers/index.ts
Expand Up @@ -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 `{}`.
Expand All @@ -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.
Expand All @@ -755,7 +755,7 @@ export class HelpersModule {
*/
probability?: number;
} = {}
): T | undefined {
): TResult | undefined {
if (this.faker.datatype.boolean(options)) {
return callback();
}
Expand Down Expand Up @@ -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.
*
Expand All @@ -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);
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -1358,7 +1358,7 @@ export class HelpersModule {
*/
store?: Record<RecordKey, RecordKey>;
} = {}
): ReturnType<Method> {
): ReturnType<TMethod> {
deprecated({
deprecated: 'faker.helpers.unique',
proposed:
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand All @@ -1420,7 +1420,7 @@ export class HelpersModule {
max: number;
};
} = {}
): T[] {
): TResult[] {
const count = this.rangeToNumber(options.count ?? 3);
if (count <= 0) {
return [];
Expand Down
12 changes: 6 additions & 6 deletions src/modules/helpers/unique.ts
Expand Up @@ -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.
Expand All @@ -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;
Expand All @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down
18 changes: 9 additions & 9 deletions src/utils/types.ts
Expand Up @@ -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.
Expand All @@ -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>>;
4 changes: 2 additions & 2 deletions test/all_functional.spec.ts
Expand Up @@ -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 = {
Expand Down
2 changes: 1 addition & 1 deletion test/scripts/apidoc/__snapshots__/signature.spec.ts.snap
Expand Up @@ -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,
}
`;
Expand Down
1 change: 1 addition & 0 deletions test/scripts/apidoc/signature.example.ts
Expand Up @@ -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.
Expand Down

0 comments on commit 2e9ed96

Please sign in to comment.