Skip to content

Commit 1c8747d

Browse files
chore: improve typings on random.objectElement (#407)
Co-authored-by: Shinigami <[email protected]>
1 parent 464cb9d commit 1c8747d

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

src/random.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -116,20 +116,29 @@ export class Random {
116116
return arrayCopy.slice(min);
117117
}
118118

119-
// TODO @Shinigami92 2022-01-28: This function needs types
120119
/**
121120
* Takes an object and returns a random key or value.
122121
*
123122
* @method faker.random.objectElement
124123
* @param object
125124
* @param field
126125
*/
127-
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
128-
objectElement(object: any = { foo: 'bar', too: 'car' }, field?: string) {
129-
const array = Object.keys(object);
126+
objectElement<T extends Record<string, unknown>, K extends keyof T>(
127+
object: T,
128+
field: 'key'
129+
): K;
130+
objectElement<T extends Record<string, unknown>, K extends keyof T>(
131+
object: T,
132+
field?: unknown
133+
): T[K];
134+
objectElement<T extends Record<string, unknown>, K extends keyof T>(
135+
object = { foo: 'bar', too: 'car' } as unknown as T,
136+
field = 'value'
137+
): K | T[K] {
138+
const array: Array<keyof T> = Object.keys(object);
130139
const key = this.faker.random.arrayElement(array);
131140

132-
return field === 'key' ? key : object[key];
141+
return field === 'key' ? (key as K) : (object[key] as T[K]);
133142
}
134143

135144
/**

0 commit comments

Comments
 (0)