LoginSignup
0
0

More than 1 year has passed since last update.

type aliasをinterfaceに変える

Last updated at Posted at 2023-01-19

typeをinterfaceに変えてみる

変数のタイプを決めるにあたって、type alias方法とinterface方法がある。
interfaceとtype aliasの違いとしては
①interfaceは"="を使わない。
②タイプを結合させたり組み合わせたりする方式の違い

①interfaceは"="を使わない。

下の二つは同じ定義です。 二つの違いはtype aliasは"="を使っていますが、interfaceは"="を使いません。
// Type Alias
type NewsFeed = {
  readonly points: number;
  readonly comments_count: number;
  read?: boolean; // ? はoptional
} 

// interface
interface NewsFeed {
  readonly points: number;
  readonly comments_count: number;
  read?: boolean;  // ? はoptional
}

②タイプを結合させたり組み合わせたりする方式の違い

interfaceは2つのタイプを合わせたり、union type やintersection typeをサポートをしていません。
interfaceは 「&」の代わりに「extends」を使用します。しかし「|」を代替するものはありません!
なので、ORの条件を表したい時はtype aliasを使うしかありません。
// Type Alias
type NewsFeed = News & {
  readonly points: number;
  readonly comments_count: number;
  read?: boolean;  // ? はoptional
} 

// interface
interface NewsFeed extends News {
  readonly points: number;
  readonly comments_count: number;
  read?: boolean;  // ? はoptional
}

interfaceの長所

interfaceは名前からも分かるように, より明確かつ明示的にできるという印象を与えます。
例えば、上記の例の場合にはnewsを拡張してnewsfeedを作ると直感的です。
「&」のように何か結合して数学演算をするような表現法よりは文字で表現するので、
コードを読む観点からだとtype aliasよりはinterfaceの方が好まれると言えます。

追加説明、readonlyとは?

readonly読み取り専用であることを表します。
なので、readonlyにした属性を変えようとするとエラーが出てしまいます。
このようにタイプの説明を豊富にしておけばおくほど、ミスを未然に防ぐことができるので、
安全なコードを作成することができます。
タイプを作成するときに時間を投資して作成しておけば、以降の実際のコードを作成するにあたりむしろ時間をたくさん稼ぐことができます。これは修正してもいいかだめか悩みをしなくても良い!になります。
これらの長所がTypeScriptの最高の長所のでは?!
0
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
0
0