抱歉,这是我第一次使用node和ts,所以我有点困惑
export const successResponseWithData = <T extends unknown>(res, data) => {
return res.status(200).json(data) as T;
};
用法
successResponseWithData<AuthToken>(res, token);
这条路对吗?
要在express中使用typescript,它提供了许多帮助器方法,如下面的RequestHandler,根据我的理解,如果您试图确保SuccessResponseWithData
应始终为特定类型,并且发送回的响应为相同类型,则可以执行以下操作:
export const interface AuthToken {
item1: <type1>
};
import {RequestHandler} from 'express';
export const apiEndPoint: RequestHandler = (req, res) => {
const resp: AuthToken = successResponseWithData();
return res.status(200).json(resp);
};
successResponseWithData: AuthToken = _ => {
// calculate token here
return token;
};