refine(refiner): PartialLens
tsrefine = <A, B extends A>(refiner: (a: A) => B | false) => PartialLens<B, A>;
tsrefine = <A, B extends A>(refiner: (a: A) => B | false) => PartialLens<B, A>;
This combinator allows you to narrow the type focused by the optic it is passed to.
It returns a new partial optic focused on the original value in its narrowed type, or undefined if the narrowing failed.
The refiner function must return the original value in its narrowed type or false if it can't be narrowed to this type.
Examples:
- On the branch of a discriminated union
tsimport {refine } from "@optics/react/combinators";typeResult <T > =| {type : "success";value :T }| {type : "failure";errorMessage : string };constresultOptic =createState <Result <number>>({type : "success",value : 42 });constsuccessOptic =resultOptic .derive (refine ((res ) =>res .type === "success" &&res ));successOptic .get (); // { type: 'success', value: 42 }resultOptic .set ({type : "failure",errorMessage : "Catastrophic meltdown" });successOptic .get (); // undefined
tsimport {refine } from "@optics/react/combinators";typeResult <T > =| {type : "success";value :T }| {type : "failure";errorMessage : string };constresultOptic =createState <Result <number>>({type : "success",value : 42 });constsuccessOptic =resultOptic .derive (refine ((res ) =>res .type === "success" &&res ));successOptic .get (); // { type: 'success', value: 42 }resultOptic .set ({type : "failure",errorMessage : "Catastrophic meltdown" });successOptic .get (); // undefined
- On a built-in type
tsimport {refine } from "@optics/react/combinators";constunknownValueOptic =createState <unknown>(42);constnumberOptic =unknownValueOptic .derive (refine ((x ) => typeofx === "number" &&x ));numberOptic .get (); // 42unknownValueOptic .set ("Hello world");numberOptic .get (); // undefined
tsimport {refine } from "@optics/react/combinators";constunknownValueOptic =createState <unknown>(42);constnumberOptic =unknownValueOptic .derive (refine ((x ) => typeofx === "number" &&x ));numberOptic .get (); // 42unknownValueOptic .set ("Hello world");numberOptic .get (); // undefined
- On a user-defined type with a type-guard
tsimport {refine } from "@optics/react/combinators";typeUser = {userName : string;};functionisUser (value : unknown):value isUser {return typeof (value asUser ).userName === "string";}conststateOptic =createState (untypedInitUser ());constmyTypeOptic =stateOptic .derive (refine ((value ) =>isUser (value ) &&value ));myTypeOptic .get (); // { userName: 'John Doe' }
tsimport {refine } from "@optics/react/combinators";typeUser = {userName : string;};functionisUser (value : unknown):value isUser {return typeof (value asUser ).userName === "string";}conststateOptic =createState (untypedInitUser ());constmyTypeOptic =stateOptic .derive (refine ((value ) =>isUser (value ) &&value ));myTypeOptic .get (); // { userName: 'John Doe' }