我正在编写一个库,我想提供更准确的类型,这样库用户就不会在我下面的示例中选择错误的类型。
如果参数 convertJSONOutput
设置为 true,此方法返回 IPlayerStats
或 IStatsItem[]
。
public async getStatsById(
userId: string,
timeWindow: TimeWindow = TimeWindow.Alltime,
convertJSONOutput: boolean = true
): Promise<IPlayerStats | IStatsItem[]> {
// Ommitted
}
问题:
我可以指定一个条件返回类型来指示将返回什么接口(interface)(取决于 convertJSONOutput
bool 参数)吗?
最佳答案
基于 bool 参数返回不同类型的最简单方法是重载:
function getStatsById(userId: string, timeWindow: TimeWindow, convertJSONOutput: true): Promise<IPlayerStats>;
function getStatsById(userId: string, timeWindow: TimeWindow, convertJSONOutput: false): Promise<IStatsItem[]>;
function getStatsById(
userId: string,
timeWindow: TimeWindow = TimeWindow.Alltime,
convertJSONOutput: boolean = true
): Promise<IPlayerStats | IStatsItem[]> {
当您调用它时,会根据参数的值推断出缩小的类型:
// Promise<IPlayerStats>
const a = getStatsById('', undefined, true);
// Promise<IStatsItem[]>
const b = getStatsById('', undefined, false);
重要的部分是每个重载都指定了确切的字面值 true
或 false
,而不是 boolean
类型。然后返回类型与此相关联。我在下面强调了这种关系。
// **** => ************
getStatsById(convertJSONOutput: true): Promise<IPlayerStats>;
我稍微调整了代码以便创建一个独立的示例,它假定 TimeWindow
、IStatsItem
和 IPlayerStats
已经存在定义:
function getStatsById(userId: string, timeWindow: TimeWindow, convertJSONOutput: true): Promise<IPlayerStats>;
function getStatsById(userId: string, timeWindow: TimeWindow, convertJSONOutput: false): Promise<IStatsItem[]>;
function getStatsById(
userId: string,
timeWindow: TimeWindow = TimeWindow.Alltime,
convertJSONOutput: boolean = true
): Promise<IPlayerStats | IStatsItem[]> {
// Ommitted
}
// Promise<IPlayerStats>
const a = getStatsById('', undefined, true);
// Promise<IStatsItem[]>
const b = getStatsById('', undefined, false);
关于typescript - 根据 bool 参数使用条件返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52801536/