LoginSignup
39
31

More than 5 years have passed since last update.

Typescriptのletとconstメモ

Posted at

Typescriptでは、変数の定義にlet(ブロックスコープ)と、const(定数)を使用することができます。

let

varと同じように使用します。

Typescript
let a = 'イエス ブロック!';

letを使用すると、関数外でもスコープを分けることができます。
下記のようにletを使用すると、ブロックの中と外で同じ変数名でもスコープを分けてくれます。

Typescript
let a = 'イエス ブロック!';
var b = 'ノー ブロック!';

if(true){
    let a = 'YES BLOCK!';
    var b = 'NO BLOCK!';
    console.log(a);//YES BLOCK!
    console.log(b);//NO BLOCK!
}

console.log(a);//イエス ブロック!
console.log(b);//NO BLOCK!

const

varと同じように使用します。

Typescript
const a = '定数だよ。書き換えないでね!';

下記のようにconstを書き換えようとするとSyntaxErrorとなります。

Typescript
const a = '定数だよ。書き換えないでね!';
a = '書き換えてやる!';//エラーになります。

また、constもletと同じくブロック単位でスコープを分けてくれます。

Typescript
const a = '定数だよ。書き換えないでね!';
if(true){
const a = 'YES CONST!';
console.log(a);//YES CONST!
}
console.log(a);//定数だよ。書き換えないでね!
39
31
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
39
31