是否有任何方法可以定义一个既需要提供两个条件参数又不需要提供条件参数的函数?例如:
function greet(firstName?: string, lastName?: string) {
if (fistName && lastName) console.log(`Hello, ${firstName} ${lastName}!`)
else console.log('Hello, World!')
}
greet('John', 'Doe') // Hello, John Doe!
greet() // Hello, World!
greet('John') // Invalid
我意识到我可以使用对象分解,创建两个方法或添加更多if语句,但是我很好奇这是否可行。谢谢!
答案 0 :(得分:2)
您可以对函数的类型使用重载:
coqdoc
还是,这有点重复而且有点丑陋。虽然可行,但我希望尽可能使用单独的功能。
一种类似的方法,使用对象而不是单独的参数:
type Greet = {
(firstName: string, lastName: string): void;
(): void;
};
const greet: Greet = (firstName?: string, lastName?: string) => {
if (firstName && lastName) console.log(`Hello, ${firstName} ${lastName}!`)
else console.log('Hello, World!')
};
greet('John', 'Doe'); // Hello, John Doe!
greet(); // Hello, World!
greet('John'); // Invalid