Home > Net >  How to create a typescript generic type with one optional property?
How to create a typescript generic type with one optional property?

Time:11-14

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[];
  }[];
}

CodePudding user response:

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

CodePudding user response:

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.

  • Related