Avatar ·

如何在 TypeScript 中传递可选函数参数并跳过其中一些?

你好!我是 TypeScript 新手,在处理具有多个可选参数的函数时遇到了问题。 假设我有一个配置数据库连接的函数: ```typescript function createConnection( host: string, port?: number, username?: string, password?: string, database?: string ): Connection { // ... 实现 } ``` 我想调用这个函数,只传递 `host`、`password` 和 `database`,跳过 `port` 和 `username`。在 JavaScript 中,我可以这样做: ```typescript createConnection('localhost', undefined, undefined, 'secret123', 'mydb'); ``` 但这看起来很糟糕——必须为每个跳过的参数传递 `undefined`。这不易读,而且容易出错,尤其是参数很多的时候。 有没有办法只传递需要的可选参数,而不指定所有前面的参数?例如在 Python 中,可以使用命名参数,但在 TypeScript/Java 中...