How to create a circularly referenced type in TypeScript?

前端 未结 4 1338
生来不讨喜
生来不讨喜 2020-12-05 13:04

I have the following code:

type Document = number | string | Array;

TypeScript complains with the following error:

4条回答
  •  忘掉有多难
    2020-12-05 13:38

    The creator of TypeScript explains how to create recursive types here.

    The workaround for the circular reference is to use extends Array. In your case this would lead to this solution:

    type Document = number | string | DocumentArray;
    
    interface DocumentArray extends Array { }
    

    Update (TypeScript 3.7)

    Starting with TypeScript 3.7, recursive type aliases will be permitted and the workaround will no longer be needed. See: https://github.com/microsoft/TypeScript/pull/33050

提交回复
热议问题