Home > Blockchain >  Define typescript guard on multiple function params
Define typescript guard on multiple function params

Time:10-02

I got a function that check if two parameters exist and are valid and I want to put a guard in typescript on both parameters to assert that they got the correct type, is it doable ?

Here is what I want to achieve (not working obviously) :

interface AbstractObject {
  name: string;
}

interface Toto extends AbstractObject {
  name: "toto";
  doTotoThings: () => void;
}

interface Titi extends AbstractObject {
  name: "titi";
  doTitiThings: () => void;
}

const isValidTotoAndTiti = (
  toto: AbstractObject | null,
  titi: AbstractObject | null
): toto is Toto & titi is Titi => // <==== is there a way to achieve this ?
  toto?.name === 'toto' && titi?.name === "titi";

CodePudding user response:

Can you define typescript guard on multiple function params

No. Type guards currently work on only one parameter.

Alternative

Package the two params into a single object parameter containing two members.

interface AbstractObject {
    name: string;
}

interface Toto extends AbstractObject {
    name: "toto";
    doTotoThings: () => void;
}

interface Titi extends AbstractObject {
    name: "titi";
    doTitiThings: () => void;
}

const isValidTotoAndTiti = (
    arg: { toto: AbstractObject | null, titi: AbstractObject | null }
): arg is { toto: Toto, titi: Titi } =>
    arg.toto?.name === 'toto' && arg.titi?.name === "titi";
  • Related