0

I'm having a hard time creating an interface that will represent a component state. Assume the following:

interface IFoo {
    fooName: string;
    fooValue: string | boolean | Array<string>
}

Then we have the following objects:

const objOne: IFoo = {
    fooName: 'objOneName',
    fooValue: true
}

const objTwo: IFoo = {
    fooName: 'objTwoName',
    fooValue: ['a', 'b', 'c']
}

Now we have an array that has those objects:

const myArray: IFoo[] = [objOne, objTwo];

Now in a React component I recieved myArray as props and need to construct the interface for the component state.

I need a new interface that will represent the state of a react component and it should look something like the following:

interface myState { 
    someProp: string;
    // The following values need to be dynamic. I don't know how many entries are there in the array 
    // in the is example: objOneName is the value of objOne[fooName] and it's type is the type of obj[fooValue]
    objOneName: boolean,
    objTwoName: Array<string>
}

1 Answer 1

1

You could create the following generic prop

interface ArbitraryProps {
    [key: string]: string | boolean | Array<string>
}

interface myState extends ArbitraryProps { 
    someProp: string;
}

I extracted ArbitraryProps as a separate interface because I imagine you want to typecheck the props you send your component by it. Also, this approach might be too loose, but that feels like something we only can take height for by re-thinking the design here...

Sign up to request clarification or add additional context in comments.

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.