【发布时间】:2021-03-14 20:36:46
【问题描述】:
我正在尝试在 typescript 中创建一个函数,该函数返回一个必须扩展给定接口的对象,但我希望该函数返回所创建对象的真实类型。 原因是函数中的对象将来可能会发生变化,我想确保它始终具有界面所需的最少道具。
示例:
interface MustExtend {
a: string;
}
function myFunc() {
// I want to enforce res to extend type MustExtend
// right now it can be of type {something: 3} and compiler will allow it
const res = {a: 'hello', b: 2}
return res;
}
const c = myFunc(); // c should be of type {a: string, b: number}, or the more concrete type generated by method
编辑:
我会尽量澄清我的问题。我希望从返回的对象中推断出函数的结果类型,而不指定 res 的类型,因为它是由许多计算生成的:
interface MustExtend {
a: string;
}
function myFunc() {
// i want to enforce res to extend type MustExtend
// right now it can be of type {something: 3} (no 'a' at all)
// and i want to make sure it exists
const res = {
a: 'hello',
b: 2,
// a million more properties here that can change over time
}
return res;
}
const c = myFunc(); // c should be of type {a: string, b: number, ...other props}
【问题讨论】:
-
你能试着解释一下吗?我以为我有你的答案,但随着我阅读你的问题,我越来越困惑。
-
本质上,我希望我的方法为在方法中创建的对象返回一个尽可能具体的值(不仅仅是
MustExtend接口)。在我的示例中,我可以这样做:const res = {somethingElse: 5}并且编译器不会大喊大叫,因为我没有强制执行任何操作。我想要两全其美:) -
function myFunc(): MustExtend { -
@nubinub 这不起作用,因为
c的类型为MustExtend而不是{a: string, b: number}类型,编译器将无法识别返回值中存在的属性b -
interface C extends MustExtend { b: number; }然后function myFunc(): C {
标签: typescript