[英]Sharing TS interface between back-end and front-end
假設我有這個快速路由器文件:
import * as express from 'express';
const router = express.Router();
export const register = v => {
router.get('/', makeGetFoo(v));
router.put('/', makePutFoo(v));
}
const makeGetFoo = v => {
interface Response extends ApiDocResponse { // <--- i want to share this interface with front-end codebase
success: true
}
return (req,res,next) => {
res.json(<Response>{success:true});
};
}
如您所見,我正在嘗試創建一個 ApiDoc 系統。 但它在前端也很有用,因此前端 TypeScript 可以知道將從 API 服務器反序列化哪些類型。
我的問題是 - 如何將后端代碼中的類型導入 Angular5 或 Angular6 代碼庫? 我知道這樣做的唯一好方法是將 ApiDoc.Response 類型放在第三個 .d.ts 文件中,然后前端和后端都可以導入該文件。 當然,這樣做的缺點是維護第三個文件,並將其與 API 路由文件正確匹配。
這樣的事情是我唯一想到的,而不必使用第三個中間文件.d.ts
文件:
import * as express from 'express';
import {RequestHandler} from 'express';
const router = express.Router();
export const register = (v: any) => {
router.get('/', MakeGet.makeGetFoo(v));
router.put('/', MakePut.makePutFoo(v));
};
interface ApiDoc {
success: boolean
}
export namespace MakeGet{
export interface Response extends ApiDoc { // <--- i want to share this interface with front-end codebase
success: true
}
export const makeGetFoo = (v: any): RequestHandler => {
return (req, res, next) => {
res.json(<Response>{success: true});
};
};
}
export namespace MakePut {
export interface Response extends ApiDoc { // <--- i want to share this interface with front-end codebase
success: true
}
export const makePutFoo = (v:any): RequestHandler => {
return (req,res,next) => {
res.json(<Response>{success:true});
};
};
}
缺點是所有名稱空間,因此必須命名太多。 但是,如果在此處放置路由和api-doc信息,但在其他地方放置控制器代碼,則可以使這些路由器文件稀疏且干凈。
因此,在另一個文件中(也許在您的前端代碼中),您可以這樣做:
import {MakeGet, MakePut} from './foo'
export interface Bar extends MakePut.Response{
}
遲到總比不到好...
typesafe-api是一個專為此任務設計的庫。
首先你定義你的 API 規范,然后它可以立即用於構建 API 客戶端和 Express 處理程序,甚至在完全類型安全的 TS 中甚至錯誤處理和請求標頭。
目的是創建一個可以使用編譯器維護的 API。
完全公開......我是圖書館的創造者,希望你覺得它有用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.