From d5b47832cb1b7ddd1736fa235f036ea40f2945c3 Mon Sep 17 00:00:00 2001 From: jamashita Date: Fri, 20 Dec 2024 20:06:55 +0900 Subject: [PATCH] =?UTF-8?q?docs:=20=E2=9C=8F=EF=B8=8F=20as=20const?= =?UTF-8?q?=E3=82=92=E3=83=97=E3=83=AA=E3=83=9F=E3=83=86=E3=82=A3=E3=83=96?= =?UTF-8?q?=E5=9E=8B=E3=80=81=E9=85=8D=E5=88=97=E3=81=AB=E9=81=A9=E7=94=A8?= =?UTF-8?q?=E3=81=97=E3=81=9F=E4=BE=8B=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../values-types-variables/const-assertion.md | 43 ++++++++++++++++--- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/docs/reference/values-types-variables/const-assertion.md b/docs/reference/values-types-variables/const-assertion.md index 6a008dd9..505ca691 100644 --- a/docs/reference/values-types-variables/const-assertion.md +++ b/docs/reference/values-types-variables/const-assertion.md @@ -4,10 +4,28 @@ sidebar_label: constアサーション「as const」 # constアサーション「as const」 (const assertion) -オブジェクトリテラルの末尾に`as const`を記述すればプロパティが`readonly`でリテラルタイプで指定した物と同等の扱いになります。 +変数宣言のときに、末尾に`as const`をつけるとその値をreadonlyにした上で、リテラル型にしてくれます。 +プリミティブ型の値だとそこまでうま味を感じにくいですが、配列やオブジェクトリテラルに対して使うと便利です。 ```ts twoslash -const pikachu = { +const str1 = "hello"; +// ^? +const str2 = "hello" as const; // これはas constがなくても同じ +// ^? +const array1 = [1, 2, 3]; +// ^? +const array2 = [1, 2, 3] as const; +// ^? +const obj1 = { + // ^? + name: "pikachu", + no: 25, + genre: "mouse pokémon", + height: 0.4, + weight: 6.0, +}; +const obj2 = { + // ^? name: "pikachu", no: 25, genre: "mouse pokémon", @@ -16,19 +34,32 @@ const pikachu = { } as const; ``` -代入はもちろんできません。 +readonlyになるため代入はもちろんできません。 ```ts twoslash -// @errors: 2540 -const pikachu = { +const array1 = [1, 2, 3]; +const array2 = [1, 2, 3] as const; +const obj1 = { + name: "pikachu", + no: 25, + genre: "mouse pokémon", + height: 0.4, + weight: 6.0, +}; +const obj2 = { name: "pikachu", no: 25, genre: "mouse pokémon", height: 0.4, weight: 6.0, } as const; + +// @errors: 2540 // ---cut--- -pikachu.name = "raichu"; +array1[0] = 4; +array2[0] = 4; +obj1.name = "raichu"; +obj2.name = "raichu"; ``` ## `readonly`と`const assertion`の違い