Reputation: 1658
I am using Typescript and React in mini project. I am new to typescript and learning right now.
So I have this state:
type State = {
field1: string,
field2: string,
field3: number,
field4: string,
}
const SomeFields = ['field1', 'field3'];
class SomeComponent extends React.PureComponent<Props, State> {
state: State = {
// Default value for above fields
}
isValid = () {
SomeFields.every((key) => {
return this.state[key].length;
});
}
}
Here this line this.state[key].length
throwing error Element implicitly has an 'any' type because type 'State' has no index signature
.
I can understand that need define type for SomeFields
, but how can I do that?
Upvotes: 2
Views: 953
Reputation: 13644
You have to implicitly tell TypeScript that this is the array of the keys of the state.
const SomeFields: Array<keyof State>
This is also improving TS experience as you will get code completion in your editor/IDE when trying to e.g. add an element to SomeFields
or use switch
etc.
Upvotes: 1