简体   繁体   中英

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?

Is this what you need?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM