Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recurse a generic within Typescript?

Typescript throws an error with the following code:

type AndType<AstT> = { type: 'And', args: [AstT] };
type TrueType = { type: 'True' };
type BaseAST = AndType<BaseAST> | TrueType;

Complaining that Type alias 'BaseAST' circularly references itself.; however, if I wrap the circular reference in an object, the types compile fine:

type AndType<AstT> = { type: 'And', args: [AstT] };
type TrueType = { type: 'True' };
type BaseAST = {value: AndType<BaseAST>} | {value: TrueType};

Why? Does anyone have a reference to the docs where this behavior is defined?

like image 341
Tomas Reimers Avatar asked Nov 07 '22 00:11

Tomas Reimers


1 Answers

The easiest solution in your case is to make the AndType type an interface as follows:

interface AndType<AstT> {
  type: 'And';
  args: [AstT];
}
type TrueType = { type: 'True' };
type BaseAST = AndType<BaseAST> | TrueType;

In general it's recommended to use interfaces for straightforward types, but this isn't always possible. The link already given should give you more in-depth information.

like image 84
vitoke Avatar answered Nov 11 '22 05:11

vitoke