lalezky
lalezky

Reputation: 554

TypeScript: two argument types for function

I need pass to function doSomething string or result of function, that returns string:

const someFunction = (href: string) => {
    ...
};

type a = () => string;

export function doSomething (href: string | a): void {
    someFunction(href);
}

But I get an error:

Argument of type 'string | a' is not assignable to parameter of type 'string'. Type 'a' is not assignable to type 'string'.

Function of type a returns string, then why I get this error?

Thanks in advance.

Upvotes: 1

Views: 223

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 174937

doSomething's href if of type string | () => string, whereas someFunction accepts only a string.

If TypeScript had allowed this, there would have been a possibility for you to pass a () => string into a function that can only deal with strings, which would have resulted in runtime errors.

It may be the case that doSomething needs to work with string-returning functions, but you can't expect someFunction to be able to, especially after you specifically defined the parameter it accepts to only be of type string.

Upvotes: 3

Related Questions