本文へスキップ
BecomeCoder

TypeScriptのエラー · エラー1

TS2322: Type is not assignable ― 違う型を代入した

宣言した型と違う型の値を入れようとすると出ます。

出るコード

let age: number = 20;
age = "21";   // number の変数に string

エラーメッセージ

error TS2322: Type 'string' is not assignable to type 'number'.

直し方

数値を入れます(age = 21)。文字列を数値化するなら Number("21") で明示的に変換します。