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

【TypeScript入門】anyとunknown型の違い

Last updated at Posted at 2021-08-23

まとめ

anyはできるだけ使わないようにし、anyの代わりにunknownを使いましょう。

  • any : どんな型でも許容する = 全く安全ではない → TypeScriptの良さがなくなる
  • unknown型:どんな型になるか不明
  • unknown型は代入した値によって方が変化する

anyについて

anyを使うと型の違う値を再代入できてしまうので、コードの質が下がってしまう。

let name: any = 'YSasago' // string型を代入
    console.log('any sample 1:', typeof name, name)

// any sample 1: string YSasago
  
    name = 29 // number型を再代入できる
    console.log('any sample 2:', typeof name, name)
  }
// any sample 2: number 29

unknown型について

unknown型を使えば、自動的に方を推論してくれる。unknown型を使って計算する際は、if文で型を確認すると、計算することができる。

    const maybeNumber: unknown = 10 // unknown
    console.log('unknown sample 1:', typeof maybeNumber, maybeNumber)
// unknown sample 1: number 10
  
    // unknown型の値を比較することができる
    const isFoo = maybeNumber === 'foo'
    console.log('unknown sample 2:', typeof isFoo, isFoo)
// unknown sample 2: boolean false
  
    // const sum = maybeNumber + 10 // object is possibly unknownのエラーが出て代入できない
  
    // number型であるか判定した後なら代入可能
    if (typeof maybeNumber === 'number') {
      const sum = maybeNumber + 10
      console.log('unknown sample 3:', typeof sum, sum)
// unknown sample 3: number 20
    }
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?