基本的な基本


タイプスクリプト対JavaScript


タイプスクリプトはJavaScriptのスーパーセットです.つまり、typescriptはJavaScriptにいくつかの機能があります.JavaScriptでは、型を定義する必要はありませんが、typescriptでは厳密に型に従っています.その結果、バグの可能性は低くなります.

基本型


いくつかの一般的な型は-number , string , boolean , undefined , null , any .

タイプスクリプトでは、10進数を格納する変数は、型の型を定義する必要がありますnumber . 大きい整数が型を得る間bigint
const total: number = 1000;
const discount: number = 1000*0.1;
const max: bigint = 10^9;
文字列
TextScriptのテキストデータを格納する変数では、変数の型を型として定義する必要がありますstring
const name: string = "Pranta";
const position: string = "Frontend Developer";
ブーリアン
これは、booleantrue or false
const loading: boolean = true|false;
アレイ
つの方法で配列の型を定義できます.最初の2つの方法は、型を明示的に定義しました.番目の方法は、タスクをinterface or type
First way -
const numbers: number[] = [1, 2, 3]
const products: string[] = ["bag", "laptop", "mobile"]
Second way -
const numbers: Array<number> = [1, 2, 3]
const products: Array<string> = ["bag", "laptop", "mobile"]
オブジェクトの配列があれば、type キーワードまたは定義interface オブジェクト内のすべてのプロパティの型を指定します.最良の使い方interface .
const IProducts {
   name: string;
   price: number;
}
const products: IProducts[] =[{ name: "Mobile", price: 10000}, { name: "Mobile", price: 10000 }];

任意
The any タイプはめったに使われません.これは、既存のJavaScriptコードで動作するのに役立ちます.すべてのデータ型が知られていない場合はany 種類
const looselyTypedVariable: any = {};
console.log(looselyTypedVariable.name); //don't give any error
しかし、使用するいくつかの欠点がありますany 種類With any TypeScriptは、そのオブジェクトに存在しないプロパティにアクセスするかどうかをエラーにしません.
const strictlyTypedVariable: {name: string} = {name:"Pranta"};
console.log(strictlyTypedVariable.age); //show error
我々は、使用を避けるように試みるべきですany それがタイプ安全性を保証しないので、必要でないとき.