基本的な基本
2453 ワード
タイプスクリプト対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";
ブーリアンこれは、
boolean
値true
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
それがタイプ安全性を保証しないので、必要でないとき.Reference
この問題について(基本的な基本), 我々は、より多くの情報をここで見つけました https://dev.to/pranta07/typescript-basics-3g9iテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol