0

suppose a component named searchBox receives tow inputs: @Input() titles: string[] and @Input() model: Object, that the number of titles values is equal to number of model properties. searchBox generates input box to number of titles length, and gets searching subjects from user and push them into a string array named titlesValues. so, searchBox should assigns the values of titlesValues to model properties peer to peer and outputs the model via @Output resultModel: Object. I tried to access each model property dynamically for assigning to, therefore I encoded this scenario in the following:

let i =0;
  Object.keys(this.model).forEach((key) => {
     this.model[key] = this.titlesValues[i];
   });

although I tested much statements and alternative codes to get desire result, but it gets bellow error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Object'.

how can I implement this scenario? Best regards.

2
  • Can you create a Stackblitz example? Commented Dec 28, 2021 at 5:55
  • its difficult to understand, can you please create stackblitz example ? Commented Dec 28, 2021 at 5:58

2 Answers 2

1

To overcome the error, you can either explicitly define model to be of type any:

@Input() model: any;

or

define a new interface for the model and use it as:

interface Model {
    [index: string]: string;
}

@Input() model: Model;
Sign up to request clarification or add additional context in comments.

5 Comments

If define input as interface Model, when we send a model shuch as: myModel={name:'', job:'', addr:'', age:''} to searchBox, is there inconsistency at searchBox input or not?
Define< @Input() model: any > works good, but we want to avoid using type 'any' in our code.
If we define Model interface, then we need to be consistent across application when using it. The component sending data to SearchBox component should ensure correct data type is sent. Also you can tweak the interface definition as per your requirement.
We implemented searchBox reusable and use it in several component which contain object type models. Therefore, we want to receive result from searcBox as an object model and send it to backend for filtering and so on
There is one more alternative, but it's not recommended as it can cause some errors to be missed :) We can disable the noImplicitAny type-checking compiler option.
0

try to change this:

@Input() titles: any[]

1 Comment

Suggestions to try something belong in comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.