2
2

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 5 years have passed since last update.

Widening Literal Typesとその防止法

Posted at

#Widening Literal Typesとは?
##letとconstの型推論の違い
###letの型推論

let name = "Hanako"
let number = 34
let attendance = true

↓これはこのように推論される

let name: string
let number: number
let attendance: boolean

###constの型推論

const name = "Hanako"
const number = 34
const attendance = true

↓これはこのように推論される

const name: "Hanako"
const number: 34
const attendance: true

→constに代入するとLiteral Typesになるが、通常のLiteral Typesではなく、Widening Literal Typesになる

→Widening Literal Typesはconstで定められた定数をさらに別の変数に代入するとLiteral Typesではなくなり、普通の型推論になってしまう現象のことを言う
ex)

const name = "Hanako"
let samename = name

↓推論結果

const name: "Hanako"
let samename: string
//他の変数に代入したらLiteral Typesではなくなる

#Widening Literal Typesを防ぐには?
##結論: const assertionを使えばよい

const name = "Hanako" as const
let name2 = name

const number = 34 as const
let number2 = number

const attendance = true as const
let attendance2 = attendance

↓推論結果

let name2: "Hanako"
let number2: 34
let attendance: true
//再代入してもLiteral Typesは失われずに保持されたままになっている
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?