LoginSignup
0
2

More than 1 year has passed since last update.

TypeScriptメモ 〜変数編〜

Last updated at Posted at 2021-11-24

型アノテーション

変数には型がある。変数には決められた型の変数しか代入できない。
型アノテーションは明示的に型を示す方法。

let x = 1 // number型が自動的に決まる
let y: number // number型を明示的に指定
y = 1
y = '1' // エラー

any型

以下のスクリプトは問題なく実行できる。xにはany型が指定されるため。

let x 
x = 123
x = 'ok'

型変換

テキストを数値に変換する時は変数に+をつける

let x = '1'
+x

または関数を利用する

let x = '1'
x = Number(x)

配列

型アノテーション

const a: number[] = [1,2,3]

配列の中身を変更できなくする

const a: readonly number[] = [1,2,3]

タプル型
配列に複数の型の値を入れられる

const a:[string, number]

enum型

多数の中から一つを選ぶ場合

enum janken { goo, choki, paa }
let goo = janken.goo

enum型は何も代入していない場合数値が入っているので注意

enum Gender { 
    male = 'male',
    female = 'female',
    other = 'other'
}
console.log(Gender.female) // 'female'

enum Season {
  spring, 
  summer, 
  autumn, 
  winter
}
console.log(Season.autumn) // 2

型のエイリアス

型名にエイリアスを設けることでわかりやすくなる。

type name = string
type age = number
let me:[name, age]

typeで型を定義する

タプル型そのものにエイリアスを作成できる。

type name = string
type age = number
type email = string
type person = [name, age, email]

const taro: person = ['taro', 20, 'foo@bar.com']

リテラル型

リテラルを方にできる

type ok = 'ok'
let ok:ok
ok = 'ok'
ok = 'foo' // error!

条件型

type msg = 'hello' | 'bye'
type id = number | string

型チェック

typeofを使用

type id = number | string
let x:id = 1
let y:id = 'taro'
console.log(typeof(x)) // 'number'
console.log(typeof(y)) // 'string'

ユーティリティ型

変数に様々な性質を付加する特殊な型。

type data = [string, number]
// 値の変更不可なdata型を定義
type ReqData = Readonly<data>

const x:data = ['foo', 20]
const y:ReqData = ['bar', 40]

シンボル

一意な値であることが保証された型。

const a:unique symbol = Symbol('ok')
const b:unique symbol = Symbol('ok')
console.log(a === b) // false
console.log(a == b) // false

nullかもしれない値

type data = [name:string, age?:number]

絶対にnullではない値

type data = [name!:string, age:number]
0
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
0
2