Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Specifying Typescript return type that implements interface with additional fields

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Is this what you need?

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading