2

I thought I am comfortable with Javascript and React, but currently suffering through typescript learning curve. I have my react state defined as:

state = {
    fields: { // list of fields
        symbol: '',
        qty: '',
        side: ''
    },
    fieldErrors: {}
};

I want to be able to use it as following (dictionary):

   onInputChange = (name :string, value :string, error :string) => {
        const fields = this.state.fields;
        const fieldErrors = this.state.fieldErrors;
        fields[name] = value;
        fieldErrors[name] = error;
        this.setState({fields, fieldErrors});
    }

How do I represent my state in terms of Typescript? I am trying something like:

interface IFields {
    name: string
}

interface IOrderEntryState {
    fields: IFields,
    fieldErrors: IFields
}

Pardon if my question sounds illiterate, totally new at this. Thanks

2 Answers 2

1

Based on your snippet, it looks like fields[name] is assigning an arbitrary key to that object. So you probably want to use an index signature to represent that instead of the hardcoded key name as you have now.

So your interfaces probably should look more like this:

interface IFields {
    // This is an index signature. It means this object can hold
    // a key of any name, and they can be accessed and set using
    // bracket notation: `this.state.fields["somekey"]`
    [name: string]: string
}

interface IOrderEntryState {
    fields: IFields,
    fieldErrors: IFields
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you want a dictionary you can declare one using generic type with index property. It would look like this:

interface Dictionary<TKey, TVal> {
    [key: TKey]: TVal;
}

interface IOrderEntryState {
    fields: Dictionary<string, string>,
    fieldErrors: Dictionary<string, string>
}

This makes IOrderEntryState.fields have arbitrary string attribute names with string values.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.