タイプスクリプトインデックス署名


ジャバスクリプトobj:{} は通常、文字列を使用してインデックス付けされます.しかし、確かに、それらを使用してインデックスを使用するnumber さらにobject キーとしての型JavaScriptオブジェクトの特定の要素をインデックスにすると、JSは常に呼び出しによって非文字列キーをstringifiedしますtoString() メソッド.So number キーはstringifyされ、object キーはtoString() 有効な文字列キーを返すメソッドです.
let obj = {
  toString(){
    console.log('toString called')
    return 'Hello'
  }
}
let foo: any = {};
foo[obj] = 'World'; // toString called
console.log(foo[obj]); // toString called, World
console.log(foo['Hello']); // World

足で撃たれる
である.object キーはJavaScriptで上記のように動作しません.通常、スクリプトはスローされますerror そうすること.
どうにか開発者が使うならobject キーなしでtoString() メソッド実装.JavaScriptでは、デフォルト値toString() V 8エンジンから来ている方法は、キーのために目的を提供します[object Object] 😖. 私は、あなたが決して欲しかったか、使われなかったと確信します[object Object] あなたの人生のオブジェクトキーとして.😂

Basically, typescript wants to save developers from getting shot in the feet, specially the beginners. It wants developers to be explicit about object index key type.


それで、error 1つ以下のように、または、それは多分異なって、毎回投げられます.object は、タイプスクリプトのオブジェクトインデックス化に使用されます."ERROR: Index signature of object type implicitly has an 'any' type"
let obj = {message:'Hello'}
let foo: any = {};

// ERROR: the index signature must be string, number ...
foo[obj] = 'World';

// Here is where you actually stored it!
console.log(foo["[object Object]"]);  // World
For number インデックス、TypeScriptは、彼らがインデックスのためによく働き、明らかに簡単にstringifiableとして動作します.

インデックス
である.Index Signature オブジェクトのインデクシングのキー型を識別します.TypeScriptのオブジェクトが作成され、インデックスがそのオブジェクトに期待されるたびにIndex Signature .
宣言する構文Index Signature 次のようになります.
type testType = {
    [<index_name>: <index_type>]: <element_type>
}
// index_name: could be any string value.
// index_type: string or number
// element_type: it could be any premitive type (string, number etc) or a custom type you want your elements to conform to.
  • インデックスシグネチャは、最後のセクションで説明されているimpliciteインデックス署名エラーを解決します.

  • オブジェクト要素を1つの型に制限するために使用できます.
    type foot = { [shot: string]: string };
    
    const shot: foot = {
        'name': 'john',
        'email': 1231    // Error
    }
    

  • あなたのインデックス署名と一緒にしたいとしてオブジェクトを形作ることができます.
    type foot = {
        color: string 
        [shot: string]: string 
    };
    
    const shot: foot = {
        'name': 'john' // Error: color attribute not available
    }
    
  • ハッピーコーディング🤞