let obj = {toString(){return'Hello' }}let foo:any= {};// ERROR: the index signature must be string, number ...foo[obj] ='World';// FIX: TypeScript forces you to be explicitfoo[obj.toString()] ='World';
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
let foo:{ [index:string] : {message:string} } = {};/** * Must store stuff that conforms to the structure *//** Ok */foo['a'] = { message:'some message' };/** Error: must contain a `message` or type string. You have a typo in `message` */foo['a'] = { messages:'some message' };/** * Stuff that is read is also type checked *//** Ok */foo['a'].message;/** Error: messages does not exist. You have a typo in `message` */foo['a'].messages;
typeIndex='a'|'b'|'c'typeFromIndex= { [kinIndex]?:number }constgood:FromIndex= {b:1, c:2}// Error:// Type '{ b: number; c: number; d: number; }' is not assignable to type 'FromIndex'.// Object literal may only specify known properties, and 'd' does not exist in type 'FromIndex'.constbad:FromIndex= {b:1, c:2, d:3};
interfaceArrStr { [key:string]:string|number; // Must accommodate all members [index:number]:string; // Can be a subset of string indexer// Just an example member length:number;}
typeFieldState= { value:string}typeFormState= { isValid:boolean }& { [fieldName:string]:FieldState }// Use it for some JavaScript object you are getting from somewhere declareconstfoo:FormState; constisValidBool=foo.isValid;constsomethingFieldState= foo['something'];// Using it to create a TypeScript object will not workconstbar:FormState= { // Error `isValid` not assignable to `FieldState isValid:false}