LoginSignup
3
0

More than 1 year has passed since last update.

[TypeScript]Symbolの活用法

Posted at

TypeScriptは構造的型付なので同じシグネチャーであれば型が異なっても受け取れてしまう
例:

class Dog {
  id: string;
  name: string
}

class Cat {
  id: string;
  name: string;
}

function callDog(dog: Dog) {
  console.log(dog);
}

const cat = new Cat("1", "");

callDog(cat); // エラーにならない

そこでSymbolを付与することで同じシグネチャーでも型が異なれば受け取ることができないようにすることができる
例:

const dogType = Symbol();
class Dog {
  [dogType]: any;
  id: string;
  name: string
}

const catType = Symbol();
class Cat {
  [catType]: any;
  id: string;
  name: string;
}

function callDog(dog: Dog) {
  console.log(dog);
}

const cat = new Cat("1", "");

callDog(cat); // エラーとなる
3
0
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
3
0