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

typescriptのanyとunknown

Last updated at Posted at 2022-05-20
let foo: any = 123;
console.log(foo.msg); // OK
let a_value1: unknown = foo;   // OK
let a_value2: any = foo;      // OK
let a_value3: string = foo;   // OK


let bar: unknown = 222; // OK 
console.log(bar.msg); // Error
let k_value1: unknown = bar;   // OK
let K_value2: any = bar;      // OK
let K_value3: string = bar;   // Error

typescriptはanyに対して、何のタイプチェックはしません。
typescriptはunknownに対して、タイプチェックをする。barはunknownなので、msgにアクセスできるかどうかは分からなくて、一応アクセスを禁止とする。
unknownは anyとunknown以外の変数に代入できない
anyは どんな変数にも代入できる

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