LoginSignup
0
0

More than 1 year has passed since last update.

Typescriptにおけるわかりにくいtypeofの挙動

Posted at

型定義と実行時でtypeof の挙動が違うので注意が必要。

$ ts-node
> 
'use strict'
> const hoge = 'hoge'
undefined
> hoge
'hoge'
> typeof hoge // 当然 'string'
'string'


> type Hoge = hoge  // type Hoge = 'hoge'を期待していたがthrowされる
[eval].ts:4:13 - error TS2749: 'hoge' refers to a value, but is being used as a type here. Did you mean 'typeof hoge'?

4 type Hoge = hoge
              ~~~~
undefined
> type Hoge = typeof hoge // この場合は type Hoge = 'hoge' と同じ
undefined
> .type _ as Hoge // 型確認
type Hoge = "hoge"
0
0
1

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