是否可以根据对象属性进行动态类型化? [英] Is it possible to have dynamic typing based on object properties?

查看:35
本文介绍了是否可以根据对象属性进行动态类型化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构:

type ErrorObject = {
  name: string,
  message: string,
}

const ALL_ERRORS: ErrorObject[] = [
   {
     name: 'No-empty-name',
     message: 'You must provide a name',
   },
   {
     name: 'No-empty-age',
     message: 'You must provide an age',
   },
   {
     name: 'No-under-18',
     message: 'You must be 18+ to continue',
   }
]

<小时>

现在我正在尝试创建一个类型来定义所有可能的错误 names,最终应该是这样的:


Now I'm trying to create a type which would define all the possible error names, that should end up like this:

type PossibleErrorNames = 'No-empty-name' | 'No-empty-age' | 'No-under-18'

这行得通,但在我的实际项目中,显然数组要大得多,更新这两种类型感觉非常缓慢,因为它们会相互依赖(如果你更新一个,你有更新另一个).

我尝试了以下方法:

const ALL_NAMES = ALL_ERRORS.map(err => `'${err.name}'`).join(' | ')
type PossibleErrorNames = ALL_NAMES

这里的问题是,这是不正确的,因为这将 ALL_NAMES 返回为

Issue here is, this is incorrect, as this would ALL_NAMES returns as

"'No-empty-name' | 'No-empty-age' | 'No-under-18'" 这是一个 string.

显然,这是 join() 的预期行为,但有没有办法

Obviously, this is the expected behaviour of join(), but is there a way I could either

  1. 将字符串转换为表达式
  2. 一些可能更优雅的名称来推断 ALL_ERRORS 数组中的类型?

推荐答案

您可以使用 作为 const 断言 并执行类似的操作,前提是在编译时知道完整数组.

You can use as const assertions and do something like this, provided that the full array is known at compile time.

type ErrorObject = {
  name: string,
  message: string
}


const ALL_ERRORS = [
   {
     name: 'No-empty-name',
     message: 'You must provide a name',
   },
   {
     name: 'No-empty-age',
     message: 'You must provide an age',
   },
   {
     name: 'No-under-18',
     message: 'You must be 18+ to continue',
   }
] as const // <----- notice here

type PossibleErrorNames = typeof ALL_ERRORS[number]["name"]
// "No-empty-name" | "No-empty-age" | "No-under-18"

游乐场

这篇关于是否可以根据对象属性进行动态类型化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆