【问题标题】:Ensure Exhaustiveness and Correctness of Object based on Const Array of Objects基于对象的Const数组保证对象的穷举性和正确性
【发布时间】:2023-02-02 23:44:34
【问题描述】:

鉴于以下ROUTES

const ROUTES = [
  { name: "Login", path: "/login", id: "login" },
  { name: "Registration", path: "/registration", id: "registration" },
  { name: "Settings", path: "/settings", id: "settings" },
] as const;

我如何创建一个类型 (SomeType) 用于:

  1. 每个id都被用作键
  2. 每个path都被用作一个值
  3. 给定ROUTES 配置,所有键 (id) 都与其值 (path) 一对一匹配

    例如:

    # correct
    const correctIdToPaths: SomeType = {
      login: "/login",
      registration: "/registration",
      settings: "/settings", 
    } as const
    
    # wrong
    const duplicatedValues: SomeType = {
      login: "/registration", # error, id "login" does not match path "/registration"
      registration: "/registration",
      settings: "/settings", 
    } as const
    
    # wrong
    const missingKey: SomeType = {
      login: "/login",
      registration: "/registration",
    } as const # error: "settings" is missing
    

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以使用 typeof ROUTES[number] 获取数组中 Routes 的并集,并创建一个映射类型,您将 remap the key 映射到 id:

    type SomeType = {[Route in typeof ROUTES[number] as Route['id']]: Route['path']}
    // type SomeType = {login: "/login", registration: "/registration", settings: "/settings"}
    

    TypeScript playground

    【讨论】:

      猜你喜欢
      • 2011-05-06
      • 2013-04-24
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多