【问题标题】:How to validate nested objects with generic type?如何验证具有泛型类型的嵌套对象?
【发布时间】:2022-08-09 02:51:07
【问题描述】:

我有一个像这样的通用类型:

type Item<T> = {a:T; B:T}

所以我想在不指定泛型类型的情况下推断具有约定字段类型的对象:

const items: Record<string, Item<?>> = {
first: {a:1, b:2},
second: {a:\'asd\'; b:\'asd\'}
third: {a:1; b:\'qwe\'} // error should here because generic isn\'t agreed
} as const
  • 这有大量的错别字。你能把它们改成minimal reproducible example吗?您应该在 IDE 中对其进行测试以确保。
  • 另请注意,items 可以是 {a: Item&lt;number&gt;, b: Item&lt;string&gt;, c: Item&lt;string | number&gt;} 类型;如果这是不可接受的,那么您能否澄清一下您只想从a 而不是ab 进行推断?
  • 没有特定类型以这种方式工作(TS 没有所谓的存在类型这是你需要的)。所以你需要一个泛型类型和一个像this 这样的泛型助手。如果满足您的需求,我可以写一个答案;如果没有,请告诉我我错过了什么。
  • @jcalz 是的,就是这样!我也对如何以您描述的方式实现对多个泛型的支持感兴趣。

标签: typescript generics types type-inference


【解决方案1】:

试试下面的代码。不过,您必须事先拥有Item 的可能类型。

type Item<T> = {a:T; b:T}

// Define the possible types
type StringItem = Item<string>
type NumberItem = Item<number>

// Use union on all of them
type Items =
  | StringItem
  | NumberItem

// And the error pop up on the right place
const items: Record<string, Items> = {
  first: {a:1, b:2},
  second: {a:'asd', b:'asd'},
  third: {a:1, b:'qwe'} // error should here because generic isn't agreed
} as const

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 2013-01-08
    • 2022-01-20
    相关资源
    最近更新 更多