0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScript 3つのType guard 備忘録

Posted at

個人用備忘録です

typeof

function toUpperCase(x: string | number) {
 if (typeof x === 'string') {
   return x.toUpperCase();
 }
 return '';
}

in

type Enginner = {
  name:string;
  role: string;
}
type Blogger = {
  name:string;
  follower: string;
}
type EngineerBlogger = Engineer & Blogger;

function describeProfile(nomadWorker: EngineerBlogger) {
  console.log(nomadWorker.name);
  if ('role' in nomadWorker) {
    console.log(nomadWorker.role);
  }
  if ('follower' in nomadWorker) {
    console.log(nomadWorker.follower);
  }
}

instanceof

Class Dog {
  speak() {
    console.log('bwbw')
  }
}
Class Bird {
  speak() {
    console.log('fuwagifu')
  }
  fly() {
    console.log('fly')
  }
}
function havePet() {
  pet.speak();
  if (pet instanceof Bird) {
    pet.fly();
  }
}
havePet(new Bird());
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?