【问题标题】:Transform an `as const` object to a more generalized type将“as const”对象转换为更通用的类型
【发布时间】:2021-03-07 23:14:04
【问题描述】:

as const const 对象派生通用类型/接口

我有这个:

const usersDefaultValues = {
  firstName: '',
  isGuest: false
} as const

而我想推导出这种类型:

type DefaultValuesSchema = {
  firstName: string
  isGuest: boolean
}

【问题讨论】:

    标签: typescript typescript-utility


    【解决方案1】:

    我认为你正在寻找这样的东西:

    const usersDefaultValues = {
      firstName: '',
      isGuest: false
    } as const
    
    type M<T> = {
      [P in keyof T]: T[P] extends boolean ? boolean : T[P] extends string ? string : never;
    }
    
    type Result = M<typeof usersDefaultValues>
    

    【讨论】:

      猜你喜欢
      • 2013-01-09
      • 2018-11-27
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 2019-08-04
      • 2013-05-23
      • 1970-01-01
      相关资源
      最近更新 更多