在运行时检测所需的TypeScript字段



我需要一种方法在运行时告诉,一个特定的字段在TypeScript接口中是否需要

应该是这样的:

interface Person {
name: string
age?: number
occupation?: string
}
const person: Person = {
// values
}
const fields = ['name', 'age', 'occupation']
fields.map(field => {
// I'm looking for a kind of `isRequired` TypeScript util,
// that can tell, whether a field in described interface is required
if (isRequired(person, field)) {
// do this
} else {
// do that
}
})

我认为,这应该是可能的,例如,当TypeScript在编译时创建一个内部数组的必填字段。

有人实现过这个吗?

这对于接口是不可能的,因为它们在运行时不存在。如果有的话,你可以用一个使用元数据的类来做到这一点,但我不知道可选状态是否保存在默认元数据中。

如果不是这种情况,您可能需要自己注释属性,这时您还可以手动创建所需属性的映射/数组。

最新更新