简体   繁体   English

递归简单对象的 TypeScript 类型?

[英]TypeScript type for recursive simple object?

I'm trying to build a type to describe a "simple object", which is an object which contains only primitive types, other objects and arrays which also only contain primitive types... or other objects and arrays, etc etc我正在尝试构建一个类型来描述一个“简单对象”,它是一个只包含基本类型的对象,其他对象和数组也只包含基本类型......或其他对象和数组等

type Primitive = string | number | boolean
type SimpleArray = Array<Primitive | SimpleObject | SimpleArray>
type SimpleObject = Record<string, Primitive | SimpleObject | SimpleArray>

However I am being told that I cannot use the SimpleObject type declaration recursively.但是我被告知我不能递归使用SimpleObject类型声明。 Is there a way to describe this type?有没有办法描述这种类型?

You can fix this by replacing Record<string, ...> with { [key: string]: ... } (which is basically the same):您可以通过将Record<string, ...>替换为{ [key: string]: ... } (基本相同)来解决此问题:

type SimpleObject = { [k: string]:  Primitive | SimpleObject | SimpleArray }

By the way, you can simplify all the above to:顺便说一句,您可以将上述所有内容简化为:

type SimpleObject = string | number | boolean | SimpleObject[] | { [key: string]: SimpleObject };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM