使用 class-validator 验证字符串文字类型

Validating String Literal Type with class-validator

我有这种类型:

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

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

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;

}

您无法按类型验证,因为类型在运行时消失了。您可以创建 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;
}
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;

}