Search code examples
typescripttypesextend

Typescript: type that has all the base attributes and allows any extensions


Let's suppose I have an interface that describes only fields I'm interested in:

interface RestResponse {
    data: {
        name: string;
        value: number;
    }
    status: number;
}

I would like to use this interface as a type for a real REST response that has more fields than these above. E.g.:

const sampleResponse = {
    data: {
        name: 'cat',
        value: 64,
        description: 'the field I won't use anywhere'
    }
    status: 200,
    isSuccessful: true
}

The question is what type sampleResponse should be? I cannot make it:

const sampleResponse: RestResponse = { ... }

because the type doesn't have fields like isSuccessful and data.description.

It's an extension of RestResponse. I expect it to have all the fields specified in the interface, but don't mind having any additional ones.


So far I tried looking at https://www.typescriptlang.org/docs/handbook/advanced-types.html, but can't find anything useful for this case.


Solution

  • You can add an indexer, which allows any key which any value

    That would look like this:

    interface RestResponse {
      data: { 
        name: string;
        value: number;
      } 
      status: number;
      [key: string]: any;
    }
    

    What is a type indexer?

    [key: string]: any is an object indexer.

    [key: string] specifies that you can add any key to the object that is of type string

    The : any after the indexer defines that the value of the key should be any and since any allows anything - you can add anything