LittleC
技术学习记录
技术交流学习

express+typescript

升级到yarn 2之后,type就炸了,typescript这玩意就像屎山一样难搞。总共有这么些包需要type:

express
express-session
multer

如果你去搜,大概率会搜到stackoverflow的内容,Property ” does not exist on type ‘Request<ParamsDictionary>’,或者Extend Express Request object using Typescript,但是根据高赞的回答,好像都不行。

用ide看看types

import * as core from 'express-serve-static-core';
/// ...省略一部分
interface Request<
    P = core.ParamsDictionary,
    ResBody = any,
    ReqBody = any,
    ReqQuery = core.Query,
    Locals extends Record<string, any> = Record<string, any>
> extends core.Request<P, ResBody, ReqBody, ReqQuery, Locals> {}

再去看看express-serve-static-core

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/04f836d8cb5e0a6652b599a42e6d6a676e073639/types/express-serve-static-core/index.d.ts#L17-L25

declare global {
    namespace Express {
        // These open interfaces may be extended in an application-specific manner via declaration merging.
        // See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/method-override/index.d.ts)
        interface Request {}
        interface Response {}
        interface Application {}
    }
}

这么说,好像只要修改这个Request就行,根据stackoverflow的一些回答,

// @types/express/index.d.ts
import 'express'
import 'multer'
declare global {
  namespace Express {

    export interface Request {
      user?: User;
    }
  }
}

tsconfig.json中,compilerOptions添加

"typeRoots": ["@types"]

然后好像就好了,上面import两个库大概是为了继承他们的type,然后再修改。

express-session同理,看types

多良心,直接把example给了,那就照着写就行。

// @types/express-session/index.d.ts
import 'express-session'


declare module 'express-session' {
  interface SessionData {
  }
}

然后,就好了。

res.locals

在一篇回答中写:

https://expressjs.com/en/api.html#res.locals

来源:https://stackoverflow.com/a/65144765/

然后再看这个

好像确实不该扩展req对象,而是用res.locals

koa

然后再另一篇回答中(https://stackoverflow.com/a/54374285/8308032),看到

koa nb

技术交流学习

express+typescript
升级到yarn 2之后,type就炸了,typescript这玩意就像屎山一样难搞。总共有这么些包需要type: express express-session multer 如果你去搜,大概率会搜到stackoverflow的内容,Pro…
扫描二维码继续阅读
2021-01-27