All of the answers here are dated as far as I can tell. In 2022 I just used the following to recursively scan a directory and save all the files and directories returned by the scan:
type AbstractDirectory = {
pathname: string;
files: string[];
};
type AbstractFileTree = string | string[] | {
[ key: string ]: AbstractFileTree;
dirpath: string;
filepaths: string[];
};
Perhaps the most common need for recursive types, is the need to use a true JSON type. JSON is a format that can be as recursive as a programmer needs it to be.
Older Versions of TypeScript (pre v3.7
) Typed JSON as Shown Here:
type Json = string | number | boolean |
null | JsonObject | JsonArray;
interface JsonObject {
[property: string]: Json;
}
interface JsonArray extends Array<Json> {}
A good example that was included in the `v3.7 release notes is demonstrated in the following snippet, which is a great solution to any recursive typing that you might be doing.
As of v3.7
or Newer, the Following is Valid TypeScript
type Json =
| string
| number
| boolean
| null
| { [property: string]: Json }
| Json[];
Both examples are recursive, but the later is a much cleaner, more readable, faster to write, easier to remember, and is just flat out a better abstract representation of what JSON is.