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?
TypeScript allows us to use more than one data type for a variable or a function parameter. This is called union type. Consider the following example of union type. In the above example, variable code is of union type, denoted using (string | number) .
TypeScript 1.4 gives programs the ability to combine one or two types. Union types are a powerful way to express a value that can be one of the several types. Two or more data types are combined using the pipe symbol (|) to denote a Union Type.
TypeScript allows you to define multiple types. The terminology for this is union types and it allows you to define a variable as a string, or a number, or an array, or an object, etc. We can create union types by using the pipe symbol ( | ) between each type.
In TypeScript, a union type variable is a variable which can store multiple type of values (i.e. number, string etc). A union type allows us to define a variable with multiple types. The union type variables are defined using the pipe ( '|' ) symbol between the types.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With