overloaded the open function for convenient type inference (#5619)

Co-authored-by: Fabian-Lars <fabianlars@fabianlars.de>
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
This commit is contained in:
Vilian Gerdzhikov
2023-04-07 18:40:25 +03:00
committed by GitHub
parent db4c9dc655
commit 1eacd51d18
4 changed files with 24 additions and 33 deletions

View File

@@ -0,0 +1,5 @@
---
"api": patch
---
Overload the dialog `open` function to have better TS result types.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -132,41 +132,27 @@ interface ConfirmDialogOptions {
* extensions: ['png', 'jpeg']
* }]
* });
* if (Array.isArray(selected)) {
* // user selected multiple files
* } else if (selected === null) {
* // user cancelled the selection
* } else {
* // user selected a single file
* }
* ```
*
* @example
* ```typescript
* import { open } from '@tauri-apps/api/dialog';
* import { appDir } from '@tauri-apps/api/path';
* // Open a selection dialog for directories
* const selected = await open({
* directory: true,
* multiple: true,
* defaultPath: await appDir(),
* });
* if (Array.isArray(selected)) {
* // user selected multiple directories
* } else if (selected === null) {
* // user cancelled the selection
* } else {
* // user selected a single directory
* }
* ```
* Note that the `open` function returns a conditional type depending on the `multiple` option:
* - false (default) -> `Promise<string | null>`
* - true -> `Promise<string[] | null>`
*
* @returns A promise resolving to the selected path(s)
*
* @since 1.0.0
*/
async function open(
options?: OpenDialogOptions & { multiple?: false }
): Promise<null | string>
async function open(
options?: OpenDialogOptions & { multiple?: true }
): Promise<null | string[]>
async function open(
options: OpenDialogOptions
): Promise<null | string[] | string>
async function open(
options: OpenDialogOptions = {}
): Promise<null | string | string[]> {
): Promise<null | string[] | string> {
if (typeof options === 'object') {
Object.freeze(options)
}