-
-
Notifications
You must be signed in to change notification settings - Fork 943
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
8 changed files
with
352 additions
and
271 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
### Stricter checking for function signature passed to `faker.helpers.multiple` method | ||
|
||
The `faker.helpers.multiple` method takes a function reference as its first parameter. Previously you may have written code like this to generate multiple values. | ||
|
||
```ts | ||
faker.helpers.multiple(faker.date.past, { count: 2 }); | ||
``` | ||
|
||
However this code has a bug - `faker.helpers.multiple` passes the loop index as the second parameter to the method, which in this case would set the `refDate` of the `faker.date.past()` call to 0, making all dates before 1970. | ||
|
||
Instead you should generally use a lambda function like | ||
|
||
```ts | ||
faker.helpers.multiple(() => faker.date.past(), { count: 2 }); | ||
``` | ||
|
||
to get the desired behavior. In v9.0, we use stricter type-checking in Typescript to detect when a function is called which is not compatible with `(v: unknown, index: number)` which can cause compile-time errors in places where previously there were potential runtime errors. | ||
|
||
**Bad** | ||
|
||
```ts | ||
faker.helpers.multiple(faker.person.firstName, ...); // ❗ | ||
// In Typescript, this is now a compile time error | ||
// Argument of type '(sex?: "female" | "male" | undefined) => string' | ||
// is not assignable to parameter of type '(v: unknown, index: number) => unknown'. | ||
``` | ||
|
||
**Good** | ||
|
||
```ts | ||
faker.helpers.multiple(() => faker.person.firstName(), ...); // ✔ | ||
``` | ||
|
||
The new types also allow for easier use-cases where the index is part of the generated data e.g. as id. | ||
|
||
```ts | ||
faker.helpers.multiple((_, index) => ({ id: index, ...}), ...); // [{id: 0, ...}, ...] | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.