Operator IS in Typescript

Can anyone explain how exactly the operator is works in typescript for type guards? There are some interfaces and custom type guards below.

  interface kekType {
   kek: string;
  }
  interface kekType2 {
   kek: string;
   lol: string;
  }
  interface kekType3 {
   keks: string;
  }

  const funckek = (akek: kekType, istrue: boolean): akek is kekType2 => istrue;
  const funckek2 = (akek: object, istrue: boolean): akek is kekType2 => istrue;

And two variables which will be casting.

  let aaa = {} as kekType;
  let aaa2 = {} as kekType3

Is it create type for if/else scope.

  if (funckek(aaa, true)) {
   console.log(aaa); // let aaa: kekType2
  }
  
  console.log(aaa); // let aaa: kekType

  if (funckek2({} as kekType3, true)) {
   console.log(aaa2); // let aaa2: kekType3
  }  

Or is it somehow combine those types if their types cannot be changed.

  if (funckek2(aaa2, true)) {
   console.log(aaa2); // let aaa2: kekType3 & kekType2
  }

I really do not understand how it actually works. I hope someone can shed some light on this.



Read more here: https://stackoverflow.com/questions/64398387/operator-is-in-typescript

Content Attribution

This content was originally published by max at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: