JavaScriptのオブジェクトリテラルをタイプスクリプトに変換する方法

9895 ワード

オブジェクトは何ですか?


JavaScriptオブジェクトリテラルは、カーソンブレースの中でカプセル化された名前値ペアのコンマ区切りのリストです.

let student = { 
  id: 1056,
  name: 'Bazuu',
  email: '[email protected]'
}  
console.log(student.name)
// Bazuu
console.log(student.email)
// [email protected]
console.log(student.phone)
// undefined (javascript)

上記のスニペットは、オブジェクトリテラルを宣言し、その内容にアクセスする方法を示します.上の例はJavaScript環境でのみ適用されますので、typescriptに変換したい場合はまずファイル拡張子を変更します.JSから.TS

let student = { 
  id: 1056,
  name: 'Bazuu',
  email: '[email protected]'
}  
console.log(student.name)
// Bazuu
console.log(student.email)
// [email protected]
console.log(student.phone)
// undefined (typescript)
// Property 'phone' does not exist on type '{ id: number; name: string; email: string; }'.ts(2339)
student1.city = 'Nairobi' 
console.log(student.city)
// Property 'city' does not exist on type '{ id: number; name: string; email: string; }'.ts(2339)

変換後のオブジェクトメンバー「電話」にアクセスしようとすると、typescriptはエラーを投げました.私は、新しいオブジェクトメンバー「都市」も加えることができませんでした.

タイプスクリプトに変換するための戦略


我々のオブジェクトリテラルを入力スクリプトに変換するときに2つの戦略を使用できます.最初の戦略はどんなタイプでもあり、2番目の戦略はインターフェイスを使用することになります.
戦略1:タイプを使用する

let student:any = { 
  id: 1056,
  name: 'Bazuu',
  email: '[email protected]'
}  
console.log(student.name)
// Bazuu
console.log(student.email)
// [email protected]
console.log(student.phone)
// undefined 
student1.city = 'Nairobi' 
console.log(student.city)
// Nairobi

タイプを使うときany , 以前にスローされたすべてのエラーが消え、既存のメンバーにアクセスできず、新しいリテラルをオブジェクトリテラルに追加できます.
使用タイプany 一時的に「エラー」をスローしますが、typescriptによって提供されるすべての型チェックを削除するので、反パターンです.
戦略2:インタフェースの使用

interface StudentInterface {
  id: number;
  name: string;
  email: string;
  phone?: number;
  city?: string;
}

let student1: StudentInterface = {
  id: 1056,
  name: "Bazuu",
  email: "[email protected]"
};
console.log(student1.name);
// Bazuu

let student2: StudentInterface = {
  id: 1192,
  name: "Morio",
  email: "[email protected]"
};
console.log(student2.id);
// 1192

let student3: StudentInterface = {
  id: 1345,
  name: "Zenga",
  email: "[email protected]",
  city: "Nairobi"
};
console.log(student3.city);
// Nairobi

オブジェクトリテラル内のメンバーオブジェクトを宣言する良い方法はインターフェイスです.それはあなたのコードをきれいに見えます、そして、また、プロジェクトが時間とともに成長するとき、あなたは全体的な開発者経験を改善するタイプ安全性とコードドキュメンテーションを得ます.
TypeScriptが指定されたオブジェクトメンバーを取得しないエラーIncaseをスローしないように、インターフェイス内の任意のオブジェクトメンバーを含めることもできます.
インターフェイスとコードロジックを分離するために、別のファイルでインターフェイスを宣言してインポートすることもできます.
私はこの短い書き込みをあなたと幸せなコーディングに役立つことを期待!