A
A
Alex2019-01-29 16:08:46
typescript
Alex, 2019-01-29 16:08:46

How correctly to register types for such function?

The following function is written in JS:

/**
 * @param {URL | string} url
 * @param {boolean} returnAsURL
 * @return {URL | string}
 */
function clearURL (url, returnAsURL = url instanceof URL) {
  url = new URL(url)

  // ...

  return returnAsURL ? url : url.toString()
}

How to describe a function in .d.tsa file so that VS Code clearly understands what type of data will be returned?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan Lopatin, 2019-01-29
@Kozack

Overloads will help . Something like that:

export function clearURL (url: URL): URL;
export function clearURL (url: string): string;
export function clearURL (url: URL | string, returnAsURL: true): URL;
export function clearURL (url: URL | string, returnAsURL: false): string;
export function clearURL (url: URL | string, returnAsURL: boolean): URL | string;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question