Skip to content

Instantly share code, notes, and snippets.

@inoyakaigor
Last active August 9, 2018 13:08
Show Gist options
  • Save inoyakaigor/6028785cf5f73f2e43eec1be8e9a1bbd to your computer and use it in GitHub Desktop.
Save inoyakaigor/6028785cf5f73f2e43eec1be8e9a1bbd to your computer and use it in GitHub Desktop.
Рекурсивный тип в Typescript

Recursive types

To define a recursive type, use this trick:

type JSONValue = string | number | boolean | JSONObject | JSONArray;

interface JSONObject {
    [x: string]: JSONValue;
}

interface JSONArray extends Array<JSONValue> { }

The trick is to make the recursive back references within interface types. This works because resolution of interface base types and interface members is deferred, whereas resolution of type aliases is performed eagerly. Ideally you'd be able to replace JSONArray with JSONValue[] in the definition of JSONValue, but certainly this is a reasonable workaround for now.

Reference: microsoft/TypeScript#3496 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment