1
0

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 1 year has passed since last update.

「as const」って何?

Posted at

as constを使ったきっかけ

こちらの記事
https://qiita.com/hayahaya925/items/31f6c262f9048d857c3f
で定数の定義の仕方を書いた

statuses.js
export const statuses = {
    NOT_START: { "id": 0, "value": "未実施" },
    DOING: { "id": 1, "value": "処理中" },
    COMPLETED: { "id":2, "value": "完了" }
};

だが、この書き方だと外部で使用したときにVScodeで値の中身を参照できない
image.png
↑型しかわからない...

ここでTypescriptを使うと中身を参照できるようになる

まず、ファイル形式をtsに変更する

statuses.ts
export const statuses = {
    NOT_START: { "id": 0, "value": "未実施" },
    DOING: { "id": 1, "value": "処理中" },
    COMPLETED: { "id":2, "value": "完了" }
};

そして、一番後ろに「as count」をつける

statuses.ts
export const statuses = {
    NOT_START: { "id": 0, "value": "未実施" },
    DOING: { "id": 1, "value": "処理中" },
    COMPLETED: { "id":2, "value": "完了" }
}as const;

こうすることで、カーソルを載せたときに値の中身を見ることができる!

image.png

そもそもas constってなんだ

as constは式の末尾につけることで値をreadonlyにするアサーション。
as constを付けない場合、export constで定数を定義していてもその中身には再代入が可能となる。
⇒再代入不可なのはSTATUSオブジェクトであり、その中身STATUS.NOT_STARTなどには再代入することができる

as constをつけることでその中身にも再代入不可となり、値が確定するので外部からも中身を参照することができるようになった...ということ?

まとめ

as constは値をreadonlyにするアサーション

オブジェクトの後ろにつけることで、オブジェクトの中身も再代入不可にすることができる。

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?