我想创建一个对象,它既可以具有基本类型,也可以具有类似于其自身的对象作为属性.我的意思是,这样的事情是错误的:
const obj: DesiredType = {
correctProp1: 'string',
correctProp2: 123,
correctProp3: true,
wrongProp4: [1, 2, 3],
prop5: {
wrongProp1: () => {}, // Is neither an object nor a primitive
wrongProp2: [1, 2, 3], // Same
correctProp3: 'other string'
}
}
我不想只使用Record<string, any>
,因为这样可以放入任何内容(函数、数组等).使用类似以下内容:
Record<string, string | number | boolean | Record<string, any>>
也是不好的,因为任何东西都可能出现在第二层
我试过这个:
type PrimitiveOrObject = string | number | boolean | Record<string, PrimitiveOrObject>; // ts(2456) type
DesiredType = Record<string, PrimitiveOrObject>;
但我得到错误ts(2456):类型别名"PrimitiveOrObject"循环引用自身.
那么,有没有办法为包含原语或与其本身类似的对象的对象创建类型别名?