'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?
Solution 1:[1]
Is this what you need?
function doThing() : FooInterface & { additionalField: string } {
return {
banana: 'blah',
additionalField: 'blah2', // Must have
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tobias S. |
