mardi 5 février 2019

Typescript: How to branch based on type

I have something like this:

interface A {
  a1: string;
  a2: number;
  a3: boolean;
}

interface B {
  b1: number;
  b2: boolean;
  b3: string;
}

function foo<K1 extends keyof A, K2 extends keyof B>(input: K1 | K2) {
  if (input keyof A ) { // <--- THIS IS WRONG!
    console.log('got A type');
  } else {
    console.log('got B type');
  }
}

foo('a1');
foo('b2');

How do I update the if statement so that it branches correctly based on type?

i've tried keyof, typeof, instanceof .... none of which are correct.

Aucun commentaire:

Enregistrer un commentaire