【问题标题】:is it possible to create a joi equivalent from typescript interface?是否可以从打字稿界面创建一个等效的 joi?
【发布时间】:2020-02-10 16:56:30
【问题描述】:

所以,现在,我的代码看起来像这样

export interface IDCARD_TYPE {
  KTP = 'KTP',
  SIM = 'SIM',
}
export interface User {
   name: string;
   email: string;
   address?: string;
   idCard: { 
     type: IDCARD_TYPE;
     account: string;
   }
}

从那个界面,我需要至少看起来像这样的 Joi 等效项:

const userSchema = joi.object().keys({
  name: joi.string(),
  email: joi.string(),
  address: joi.string(),
  idCard: joi.object().keys({
    type: joi.string(),
    account: joi.string(),
  }),
});

这就是我到目前为止所得到的:

export interface JoiGeneric<X> extends joi.ObjectSchema {
  keys(params: { [K in keyof X]: JoiOf<X[K]> }): this;
}

export function joiGeneric<X>(): JoiGeneric<X> {
   return joi.object() as JoiGeneric<X>;
}

export type  JoiOf<X> = X extends string ? joi.StringSchema :
X extends number ? joi.NumberSchema :
X extends Date ? joi.DateSchema :
X extends IAnyX ? joi.AnySchema : // this one can be ignored for now.
X extends object ? JoiGeneric<X> :
never

我会像这样使用它:

const userSchema: JoiOf<User> = joiGeneric<User>().keys({
   name: joi.string().required(),
   email: joi.string().required(),
   // how can I make it so that address field is required here?
   idCard: joiGeneric<User['idCard']>().keys({
     type: joi.string().required(),
     account: joi.string().required(),
   }),
});

但我的问题是,在定义 userField 时,字段 address 是可选的。

如何在创建架构时使字段地址为必填项?

【问题讨论】:

    标签: javascript typescript typescript-typings typescript-generics


    【解决方案1】:

    如果address 字段是可选的,我认为最好还是定义该字段并在不需要时将字符串留空。

    export interface User {
       name: string;
       email: string;
       address: string;
       idCard: { 
         type: IDCARD_TYPE;
         account: string;
       }
    }
    

    我不赞成可选字段,因为它们 (1) 要求开发人员编写更多代码来处理字段被引用但不存在时发生的错误;这反过来又增加了开发代码所需的时间、源代码的大小以及运行代码所需的时间,并且 (2) 产生了一个对象的几种组合,在我看来真的应该被处理为新类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-27
      • 2018-02-04
      • 2021-02-02
      • 2017-12-27
      • 2021-12-13
      • 1970-01-01
      • 2016-03-04
      • 2021-12-24
      相关资源
      最近更新 更多