根据 TypeScript 中的参数值更改返回类型

2024-04-16

我有以下功能:

function doThing(shouldReturnObject: boolean): string | object {
    return shouldReturnObject ? { hello: 'world' } : 'hello world';
}

我希望返回值是一个对象shouldReturnObject等于 true,但为 false 时为字符串。


解决方案是重载该函数。为每个参数值重载该函数并更新返回类型,如下所示:

doThing(shouldReturnObject: true):  object
doThing(shouldReturnObject: false): string
doThing(shouldReturnObject: boolean): string | object {
  return shouldReturnObject ? { hello: 'world' } : 'hello world';
}

如果参数是对象,也可以实现这一点。例如:

interface DoThingsSettings {
  lazyLoading: boolean;
}

doThing(settings: { lazyLoading: false} &  DoThingsSettings): object[]
doThing(settings: { lazyLoading: true} &  DoThingsSettings): string[]
doThing(settings: DoThingsSettings):  object[] |  string[] {
  return settings.lazyLoading ? [{ name: 'Peter' }] : ['/user/1'];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据 TypeScript 中的参数值更改返回类型 的相关文章

随机推荐