1

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.

1
  • 5
    An ice cream dispenser gives out ice cream, then why can't I eat ice cream dispensers? A string and a string-producing function are two entirely different things, and extra code is needed to distinguish one type from another (wiith yet more code then to run the function and obtain the string). Commented Dec 25, 2018 at 7:50

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.