77

I'm trying to have a property with a union type of a lambda function or a string.

class TestClass {
    name: string | () => string;
}

Non-working TS playground sample can be accessed here.

But the TS compiler gives an error: "[ts] Member 'string' implicitly has an 'any' type."

Is the type declared incorrectly? Or is there a workaround for this?

2 Answers 2

151

You just need an extra set of parenthesis.

class TestClass {
    name: string | (() => string);
}

The compiler is trying to do (string | ()) => string if you don't use them, because of precedence.

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

Comments

17

As Titian already mentioned, you have to use parenthesis.

class TimePeriod {
    name: string | (() => string);
}

Another approach is to use a type alias:

type ATypeName = () => string;
class TimePeriod {
    name: string | ATypeName;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.