Skip to content

Commit bdcceec

Browse files
Add docs for new lenses methods (#1167)
* Add docs for new methods * Added docs how to extends lens --------- Co-authored-by: Bill <[email protected]>
1 parent d6e76a7 commit bdcceec

File tree

1 file changed

+265
-0
lines changed

1 file changed

+265
-0
lines changed

src/content/docs/uselens.mdx

Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,10 @@ These are the core methods available on every lens instance:
7777
| [`reflect`](#reflect) | Transform and reshape lens structure | `Lens<NewStructure>` |
7878
| [`map`](#map) | Iterate over array fields (with useFieldArray) | `R[]` |
7979
| [`interop`](#interop) | Connect to React Hook Form's control system | `{ control, name }` |
80+
| [`narrow`](#narrow) | Type-safe narrowing of union types | `Lens<SubType>` |
81+
| [`assert`](#assert) | Runtime type assertion for type narrowing | `void` |
82+
| [`defined`](#defined) | Exclude null and undefined from lens type | `Lens<NonNullable>` |
83+
| [`cast`](#cast) | Force type change (unsafe) | `Lens<NewType>` |
8084
8185
---
8286
@@ -344,6 +348,193 @@ function ControlledInput({ lens }: { lens: Lens<string> }) {
344348
}
345349
```
346350

351+
<Admonition type="info" title="Type System Escape Hatches">
352+
353+
The `narrow`, `assert`, `defined`, and `cast` methods serve as escape hatches for current TypeScript limitations with lens type compatibility. These methods address scenarios where you need to pass lenses with wider types to components expecting narrower types.
354+
355+
These workarounds will become less necessary once [issue #38](https://github.com/react-hook-form/lenses/issues/38) is resolved, which aims to improve lens type variance to allow more natural type narrowing and component composition.
356+
357+
</Admonition>
358+
359+
### narrow {#narrow}
360+
361+
The `narrow` method provides type-safe narrowing of union types, allowing you to tell the type system which branch of a union you want to work with. This is particularly useful when working with discriminated unions or optional values.
362+
363+
#### Manual Type Narrowing
364+
365+
Use the single generic parameter to manually narrow the type when you know (by external logic) what the value should be:
366+
367+
```tsx copy
368+
// Lens<string | number>
369+
const unionLens = lens.focus("optionalField")
370+
371+
// Narrow to string when you know it's a string
372+
const stringLens = unionLens.narrow<string>()
373+
// Now: Lens<string>
374+
```
375+
376+
#### Discriminated Union Narrowing
377+
378+
Use the discriminant overload to narrow based on a specific property value:
379+
380+
```tsx copy
381+
type Animal = { type: "dog"; breed: string } | { type: "cat"; indoor: boolean }
382+
383+
const animalLens: Lens<Animal> = lens.focus("pet")
384+
385+
// Narrow to Dog type using discriminant
386+
const dogLens = animalLens.narrow("type", "dog")
387+
// Now: Lens<{ type: 'dog'; breed: string }>
388+
389+
const breedLens = dogLens.focus("breed")
390+
// Type-safe access to dog-specific properties
391+
```
392+
393+
<Admonition type="important" title="Type Safety">
394+
395+
The `narrow` method performs type-level operations only. It doesn't validate the runtime value - use it when you have external guarantees about the value's type (e.g., from validation, conditional rendering, or runtime checks).
396+
397+
</Admonition>
398+
399+
### assert {#assert}
400+
401+
The `assert` method provides runtime type assertions that convince TypeScript the current lens is already the desired subtype. Unlike `narrow`, this is a type assertion that modifies the current lens instance.
402+
403+
#### Manual Type Assertion
404+
405+
Use the generic parameter to assert the lens is already the desired type:
406+
407+
```tsx copy
408+
function processString(lens: Lens<string>) {
409+
// Work with string lens
410+
}
411+
412+
const maybeLens: Lens<string | undefined> = lens.focus("optional")
413+
414+
// After your runtime check
415+
if (value !== undefined) {
416+
maybeLens.assert<string>()
417+
processString(maybeLens) // Now TypeScript knows it's Lens<string>
418+
}
419+
```
420+
421+
#### Discriminant-Based Assertion
422+
423+
Use the discriminant overload when you're in a conditional branch:
424+
425+
```tsx copy
426+
type Status =
427+
| { type: "loading" }
428+
| { type: "success"; data: string }
429+
| { type: "error"; message: string }
430+
431+
const statusLens: Lens<Status> = lens.focus("status")
432+
433+
// In a conditional branch
434+
if (selected.type === "success") {
435+
statusLens.assert("type", "success")
436+
// Within this block, statusLens is Lens<{ type: 'success'; data: string }>
437+
const dataLens = statusLens.focus("data") // Type-safe access
438+
}
439+
```
440+
441+
<Admonition type="warning" title="Runtime Safety">
442+
443+
`assert` is a type-only operation that doesn't perform runtime validation. Ensure your assertions are backed by proper runtime checks to avoid type safety violations.
444+
445+
</Admonition>
446+
447+
### defined {#defined}
448+
449+
The `defined` method is a convenience function that narrows the lens type to exclude `null` and `undefined` values. This is equivalent to using `narrow<NonNullable<T>>()` but provides a more expressive API.
450+
451+
```tsx copy
452+
const optionalLens: Lens<string | null | undefined> = lens.focus("optional")
453+
454+
// Remove null and undefined from the type
455+
const definedLens = optionalLens.defined()
456+
// Now: Lens<string>
457+
458+
// Use after validation
459+
if (value != null) {
460+
const safeLens = optionalLens.defined()
461+
// Work with guaranteed non-null value
462+
}
463+
```
464+
465+
**Common use cases:**
466+
467+
```tsx copy
468+
// Form validation
469+
const emailLens = lens.focus("email") // Lens<string | undefined>
470+
471+
function validateEmail(email: string) {
472+
// validation logic
473+
}
474+
475+
// After confirming value exists
476+
if (formState.isValid) {
477+
const validEmailLens = emailLens.defined()
478+
// Pass to functions expecting non-null values
479+
validateEmail(validEmailLens.interop().control.getValues())
480+
}
481+
```
482+
483+
### cast {#cast}
484+
485+
The `cast` method forcefully changes the lens type to a new type, regardless of compatibility with the original type. This is a powerful but potentially **unsafe** operation that should be used with extreme caution.
486+
487+
```tsx copy
488+
// Cast from unknown/any to specific type
489+
const unknownLens: Lens<unknown> = lens.focus("dynamicData")
490+
const stringLens = unknownLens.cast<string>()
491+
// Now: Lens<string>
492+
493+
// Cast between incompatible types (dangerous!)
494+
const numberLens: Lens<number> = lens.focus("count")
495+
const stringLens = numberLens.cast<string>()
496+
// Type system now thinks it's Lens<string>, but runtime value is still number
497+
```
498+
499+
**Safe usage patterns:**
500+
501+
```tsx copy
502+
// Working with external APIs returning 'any'
503+
function processApiData(data: any) {
504+
const apiLens = LensCore.create(data)
505+
506+
// Cast after runtime validation
507+
if (typeof data.user === "object" && data.user !== null) {
508+
const userLens = apiLens.focus("user").cast<User>()
509+
return <UserProfile lens={userLens} />
510+
}
511+
}
512+
513+
// Type narrowing when you have more information
514+
interface BaseConfig {
515+
type: string
516+
}
517+
518+
interface DatabaseConfig extends BaseConfig {
519+
type: "database"
520+
connectionString: string
521+
}
522+
523+
const configLens: Lens<BaseConfig> = lens.focus("config")
524+
525+
// After checking the type at runtime
526+
if (config.type === "database") {
527+
const dbConfigLens = configLens.cast<DatabaseConfig>()
528+
// Now can access database-specific properties
529+
}
530+
```
531+
532+
<Admonition type="danger" title="Use with Extreme Caution">
533+
534+
`cast` bypasses TypeScript's type system entirely. It can lead to runtime errors if the underlying data doesn't match the asserted type. Always validate data at runtime before using `cast`, or prefer safer alternatives like `narrow` when possible.
535+
536+
</Admonition>
537+
347538
### useFieldArray
348539

349540
Import the enhanced `useFieldArray` from `@hookform/lenses/rhf` for seamless array handling with lenses.
@@ -605,6 +796,80 @@ function App() {
605796
}
606797
```
607798

799+
#### Extending lenses
800+
801+
You can extend the basic lens functionality by adding custom methods to the `LensBase` interface. This is useful when you need additional methods that aren't available in the default lens API.
802+
803+
For example, let's add a `getValue` method to the lens that allows you to easily retrieve the current form values.
804+
805+
**Step 1: Create the type declarations file**
806+
807+
Create a `lenses.d.ts` file to extend the basic interface with the methods you want:
808+
809+
```typescript
810+
declare module "@hookform/lenses" {
811+
interface LensBase<T> {
812+
getValue(): T
813+
}
814+
}
815+
816+
export {}
817+
```
818+
819+
**Step 2: Create the custom lens core implementation**
820+
821+
Create a `MyLensCore.ts` file with the actual runtime implementation:
822+
823+
```typescript
824+
import type { FieldValues } from "react-hook-form"
825+
import { LensCore } from "@hookform/lenses"
826+
827+
export class MyLensCore<T extends FieldValues> extends LensCore<T> {
828+
public getValue() {
829+
return this.control._formValues
830+
}
831+
}
832+
```
833+
834+
**Step 3: Create the custom hook**
835+
836+
Create a `useMyLens.ts` file that accepts control and returns the lens as usual:
837+
838+
```typescript
839+
import { type DependencyList, useMemo } from "react"
840+
import type { FieldValues } from "react-hook-form"
841+
842+
import { LensesStorage, type Lens, type UseLensProps } from "@hookform/lenses"
843+
import { MyLensCore } from "./MyLensCore"
844+
845+
export function useMyLens<TFieldValues extends FieldValues = FieldValues>(
846+
props: UseLensProps<TFieldValues>,
847+
deps: DependencyList = []
848+
): Lens<TFieldValues> {
849+
return useMemo(() => {
850+
const cache = new LensesStorage(props.control)
851+
const lens = new MyLensCore<TFieldValues>(
852+
props.control,
853+
"",
854+
cache
855+
) as unknown as Lens<TFieldValues>
856+
857+
return lens
858+
}, [props.control, ...deps])
859+
}
860+
```
861+
862+
**Step 4: Use your extended lens**
863+
864+
Now you can use this hook as usual and you have the new method with correct TypeScript support:
865+
866+
```typescript
867+
const lens = useMyLens(form)
868+
lens.getValue() // Your custom method is now available with full type support
869+
```
870+
871+
This pattern allows you to add any custom functionality to lenses while maintaining full type safety and compatibility with the existing lens API.
872+
608873
<Admonition type="tip" title="Questions or Feedback?">
609874

610875
Found a bug or have a feature request? Check out the [GitHub repository](https://github.com/react-hook-form/lenses) to report issues or contribute to the project.

0 commit comments

Comments
 (0)