根据布尔参数返回不同类型的最简单方法是重载:
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);