我試圖找出一種使用匯出模塊串列作為型別的方法。假設我有三個檔案:
// schemas/auth.ts
import Joi, { Schema } from 'joi';
export const login: Schema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
});
// schemas/index.ts
import { login } from './auth';
export default { login };
并且,對于驗證中間件:
import { NextFunction, Request, Response } from 'express';
import schemas from '../schemas';
export default (schema: string) => {
if (!schemas.hasOwnProperty(schema))
throw new Error(`'${schema}' validator is not exist`);
return async function (req: Request, _res: Response, next: NextFunction) {
try {
const validated = await schemas[schema].validateAsync(req.body);
req.body = validated;
next();
} catch (err) {
if (err.isJoi) console.log(err);
// return next(createHttpError(422, { message: err.message }));
next();
}
};
};
此驗證器將無法正常作業,因為 TypeScript 無法確定傳入的schema字串是否在 中具有相應的模塊schemas,因此我不得不以某種方式說“引數schema只能是匯出模塊的名稱之一”。實作這一目標的最佳方法是什么?
uj5u.com熱心網友回復:
您可以使用 typekeyof typeof schemas使驗證功能只接受作為schemas.
TS 檔案:https : //www.typescriptlang.org/docs/handbook/2/keyof-types.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/340957.html
標籤:打字稿
