在typescript中,如何根据前面的布尔参数判断是否需要添加另一个参数?

In typescript, how do you determine whether another parameter needs to be added based on the previous Boolean parameter?

这是一个例子

const fn = (bool, str1, str2) => {
    // do something
}

如果bool为真,则需要传入str2,否则不需要

您可以像这样定义重载:

function fn(bool: false, str1: string): void;
function fn(bool: true, str1: string, str2: string): void;
function fn(bool: boolean, str1: string, str2?: string): void {
    // do something
}

fn(false, "a"); // OK
fn(false, "a", "b"); // Error
fn(true, "a"); // Error
fn(true, "a", "b"); // OK

Playground