Search code examples
typescripttype-declaration

How to recursively declare this type in TypeScript?


What I want to declare is a type that can hold a string, or a function that returns a string, or a function that returns a function that returns a string, and so forth.

Basically something like this, but recursively and possibly without the arbitrary limitation of 5 functions I have now.

type NestedStringProvider =
string |
(() => string) |
(() => () => string) |
(() => () => () => string) |
(() => () => () => () => string) |
(() => () => () => () => () => string);

So that I could do:

let s: NestedStringProvider;
s = "foobar"; // ok
s = function () { return () => "string" }; // ok
s = 1; // error

I'm using TypeScript 3.1.6. I would be ready to upgrade if that helps with my problem.


Solution

  • You can simply refer to your type recursively:

    type NestedStringProvider =
        | string
        | (() => NestedStringProvider);
    

    Checkout a playground link