Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Union type with a function

Tags:

typescript

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?

like image 838
nipuna777 Avatar asked Dec 11 '17 08:12

nipuna777


People also ask

Does TypeScript have union types?

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) .

How do you declare a union type variable in TypeScript?

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.

How do I assign two TypeScript types?

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.

When would one use a union type in TypeScript?

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.


2 Answers

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.

like image 84
Titian Cernicova-Dragomir Avatar answered Oct 16 '22 19:10

Titian Cernicova-Dragomir


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;
}
like image 10
str Avatar answered Oct 16 '22 18:10

str