指定Typescript返回类型,实现带有附加字段的接口



所以我有一个函数返回一个扩展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
}
}

最新更新