1
type AssertFuncSync = (...args: any[]) => boolean
type AssertFunc = (...args: any[]) => Promise<boolean>

I have defined two types in typescript above.

Now, in the function demoFunc, I need to check whether the parameter is an AssertFuncSync or an AssertFunc. How can I achieve it?

const demoFunc = (test_func: AssertFunc | AssertFuncSync): any => {
    if (test_func is an AssertFunc) {
        console.log("it belongs to AssertFunc")
    }else{
        console.log("it belongs to AssertFuncSync")
    }
}
zzzgoo
  • 1,974
  • 2
  • 17
  • 34
  • 2
    TypeScript does not support type check on run time, ur best bet would be using javascript [instanceOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof). [Refer to this thread](https://stackoverflow.com/a/54819677/7514001) – johnson lai Mar 08 '19 at 06:53

2 Answers2

0

To achieve this I believe you can use the typescripts' type guard feature.docs here

interface Bird {
    fly();
    layEggs();
}

interface Fish {
    swim();
    layEggs();
}

function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}
Kushagra Saxena
  • 671
  • 5
  • 17
0

you can use discriminant property in your type. it means that you have to have same key in both type and then just ask on that key. typescript can narrow type in precompilation time, (not in runetime ofc)

type AssertFuncSync = {
  isSync: true,
  syncFunc: (...args: any[]) => boolean,
};

type AssertFunc = {
  isSync: false,
  asyncFunc: (...args: any[]) => Promise<boolean>,
};

const demoFunc = (testFunc: AssertFunc | AssertFuncSync): any => {
  switch (testFunc.isSync) {
    case true:
      testFunc.syncFunc(); // no error
      testFunc.asyncFunc(); // error: Property 'asyncFund' does not exist on type 
                                     'AssertFuncSync'.
      break;
    case false :
      testFunc.syncFunc(); // error: Property 'syncFunc' does not exist on type 
                                     'AssertFunc'
      testFunc.asyncFunc();  // no error
  }
};

check this out

as you mentioned, this is too much verbose. you can use if statement instead of switch case...

const demoFunc = (testFunc: AssertFunc | AssertFuncSync): any => {
  if (testFunc.isSync) {
    testFunc.syncFunc(); // no error
  } else {
    testFunc.asyncFunc();  // no error
  }
};
Juraj Kocan
  • 2,648
  • 1
  • 15
  • 23