M
M
miliko mikoyan2019-07-02 06:49:23
typescript
miliko mikoyan, 2019-07-02 06:49:23

How does typescript compare declared types?

interface SStitle {
  title: string;
  }
  const x:SStitle = { title: "AZ5"};

  if(???){...}esle{...} //x === SStitle

I have an SStitle interface. I want to write in if (???) such logic that type X is compared with type SStitle.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Karo, 2019-07-02
@miliko0022

Typescript does not exist in runtime, bare js remains, i.e. such a check will not work
Or do a check on indirect signs, such as

function isSStitle(arg: any): arg is SStitle {
    return arg && typeof arg.title === 'string';
}

Type guard is used here https://basarat.gitbooks.io/typescript/docs/types/...
Or do it as a class and through instanceof:
class SStitle {
  title: string;
  constructor(title: string) {
    this.title = title;
  }
}
  const x:SStitle = new SStitle("AZ5");

  if(x instanceof SStitle){...}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question