繁体   English   中英

指定使用附加字段实现接口的 Typescript 返回类型

[英]Specifying Typescript return type that implements interface with additional fields

所以我有一个函数,它返回一个扩展 FooInterface 类的对象。 我想将返回类型限制为实现 FooInterface 但还有一个附加字段的类。

interface FooInterface {
   readonly banana: string
}

function doThing() : FooInterface {

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

如何定义doThing()的返回类型以指定包含additionalField字段? 如果有办法只使用函数定义来做到这一点?

这是你需要的吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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