【问题标题】:Validating String Literal Type with class-validator使用类验证器验证字符串文字类型
【发布时间】:2020-09-10 17:35:17
【问题描述】:

我有这种类型:

export type BranchOperatorRole = 'none' | 'seller' | 'operator' | 'administrator';

我可以使用哪个类验证器装饰器来验证属性是否具有这些值之一?

import { IsEmail, IsString, Contains } from "class-validator";

export type BranchOperatorRole = 'none' | 'seller' | 'operator' | 'administrator';

export class AddBranchOperatorRequest extends User {

    @IsEmail()
    email: string;

    @Contains(BranchOperatorRole )
    role: BranchOperatorRole;

}

【问题讨论】:

    标签: typescript class-validator


    【解决方案1】:
    const roles = ['none', 'seller', 'operator', 'administrator'] as const;
    export type BranchOperatorRole = typeof roles[number];
    
    export class AddBranchOperatorRequest extends User {
    
        @IsEmail()
        email: string;
    
        @IsIn(roles)
        role: BranchOperatorRole;
    
    }
    

    【讨论】:

    • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提出问题的人。请edit您的回答添加解释并说明适用的限制和假设。
    【解决方案2】:

    您无法按类型进行验证,因为类型在运行时会消失。您可以创建 Enum 并使用 IsEnum 装饰器进行验证。 Example

    在你的情况下尝试这样的事情:

    export enum BranchOperatorRoleEnum = {
      none=1,
      seller=2,
      // other
    }
    
    class AddBranchOperatorRequest {
        @IsEnum(BranchOperatorRoleEnum)
        role: BranchOperatorRole;
    }
    

    甚至用数组代替枚举

    export type BranchOperatorRole = 'none' | 'seller' | 'operator' | 'administrator';
    
    export const BranchOperatorRoles: BranchOperatorRole[] = [
      'none',
      'seller',
      // other
    ]
    
    class AddBranchOperatorRequest {
        @IsEnum(BranchOperatorRoles)
        role: BranchOperatorRole;
    }
    

    【讨论】:

    • 有点傻,你的代码加倍了。将硬编码值加倍。一定会有更好的办法。我相信!
    猜你喜欢
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 2020-08-18
    • 2017-10-16
    • 2012-03-13
    • 2019-05-01
    相关资源
    最近更新 更多