首页 > 解决方案 > 将“as const”对象转换为更通用的类型

问题描述

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

我有这个:

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

我想派生这种类型:

type DefaultValuesSchema = {
  firstName: string
  isGuest: boolean
}

标签: typescripttypescript-utility

解决方案


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

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>

推荐阅读