2

I'm using react with typescript and I have this:

interface SomeProps {
  stuff: {
    optionalStuff?: object[];
  }[];
}

The only problem with this approach is that if I try to insert any property besides optionalStuff inside the stuff object[], it will fail because those properties are not listed.

How can I do something like:

interface SomeProps {
  stuff: {
    ACCEPTS_ANY_GENERIC_STUFF_INSIDE: string | number | object | undefined
    optionalStuff?: object[];
  }[];
}

2 Answers 2

2

You could make SomeProps generic, so you could specify what other optional fields would stuff accept. In the example below, stuff except optionalStuff takes also foo field.

type SomeProps<T> = {
  stuff: ({
    optionalStuff?: object[];
  } & T)[];
}

const arr: SomeProps<{ foo: string }> = {
  stuff: [{
    optionalStuff: [],
    foo: 'abc'
  }]
}

Typescript playground

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

Comments

1

The previous answer is correct, but in case you don't know in advance or the type of objects in stuff only share the optionalStuff array but not the other keys, you could use an index signature.

interface SomeProps {
  stuff: {
    optionalStuff?: object[];
    [key: string]: string | number | object | undefined;
  }[];
}

Then you get type checking for optionalStuff but the objects can be extended with any other property.

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.