【问题标题】:Type for any JSON-like object with specific subtypes具有特定子类型的任何类 JSON 对象的类型
【发布时间】:2020-04-30 08:38:21
【问题描述】:

我需要限制用户只使用类似 JSON 的道具(null、字符串、数字、布尔值和带有此原语的对象或数组)。

我有纯 JSON 的类型:

export type SerializableObject = { [key: string]: Serializable }
export interface SerializableArray extends Array<Serializable> {}
export type Serializable = null | string | number | boolean | SerializableArray | SerializableObject

但有些类型是不可分配的:

[...]    
Type '{ tabId: string; tabs: TabData[]; }' is not assignable to type 'SerializableObject'.

TabData 是:

interface TabData {
  label: string
  body: string
}

是否可以编写类型,包括更具体的类型,但仍类似于 JSON?

【问题讨论】:

  • 这里的问题是由microsoft/TypeScript#15300引起的; TabData 是一个 interface,它没有隐式索引签名,这与 type 别名不同。我建议使用对象文字或类型别名,或者将您的 Serializable 更改为通用约束而不是特定类型
  • 如果你想让我把这些变成答案,或者它们是否不能满足你的需求,请告诉我(如果没有,为什么不)

标签: typescript types typescript-typings


【解决方案1】:

我建议研究 type-fest 库及其 JsonValue 类型。根据您的用例,它可能适合您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 2015-01-18
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多