Home > database >  Specifying Typescript return type that implements interface with additional fields
Specifying Typescript return type that implements interface with additional fields

Time:05-18

So I have a function that returns an object which extends the FooInterface class. I want to restrict the return type to classes that implement FooInterface but also have an additional field.

interface FooInterface {
   readonly banana: string
}

function doThing() : FooInterface {

    return { 
        banana: 'blah',
        additionalField: 'blah2', // Must have
    }
}

How can I define the return type of doThing() to specify that additionalField be included? If there a way to do this just using the function definition?

CodePudding user response:

Is this what you need?

function doThing() : FooInterface & { additionalField: string } {
    return { 
        banana: 'blah',
        additionalField: 'blah2', // Must have
    }
}
  • Related