【发布时间】:2021-06-14 23:04:39
【问题描述】:
我正在尝试编写一个需要一些接口的类型定义,如下所示:
interface IMyInterface {
name: string
subobject: {
boolField: boolean
}
}
然后让OptionsTransformer 包装它,对于每个key-value 对,保持键相同,但将值更改为新类FieldOptions<type>。例如:
const transformed: OptionsTransformer<IMyInterface> = {
name: new FieldOptions<string>(),
subobject: {
boolField: new FieldOptions<boolean>()
}
}
这是因为我知道TS 接口在运行时会消失,因此您无法在运行时真正检查它们。我希望能够编写如下函数(我的实际用例是在发布请求的正文中输入:我知道它应该是什么样子,并想验证它看起来像那样):
const runtimeVerifier<T> = (
options: OptionsTransformer<T>, input: Record<string, unknown>
) => {
//for each value in input, run the it's verifier. If it's a sub-object,
//recurse and do runtime verifier on the sub-object.
}
另一个要求是,在编译时,如果我向IMyInterface 添加一个字段,我希望TS 编译器给我一个错误,例如“Your optionsTransformer is missing the field 。”。
我对这个定义已经很远了:
//this class doesn't matter, but here for completeness
class FieldOption<T> {}
export interface IValidBody {
[x: string]: boolean | string | number | IValidBody
}
export type OptionsTransformer<T extends IValidBody> = {
[key in keyof T]-?: T[key] extends IValidBody
? IOptionsForFields<T[key]>
: FieldOption<T[key]>
}
但我在子对象上遇到了一些非常复杂的错误,并且无法破译它们。
任何帮助将不胜感激。
【问题讨论】:
-
你试过什么?
OptionsTransformer和FieldOption在哪里? -
@AlirezaAhmadi 抱歉,
OptionsTransformer接口在“我尝试过的部分”中命名错误。我在编辑中重命名了它。 FieldOption 无关紧要,但为了清楚起见,我也添加了它。
标签: typescript typescript-typings typescript-generics