개발하자

유형 스크립트: 익스프레스 연장.자체 클래스가 있는 세션 인터페이스

Cuire 2023. 2. 18. 19:37
반응형

유형 스크립트: 익스프레스 연장.자체 클래스가 있는 세션 인터페이스

나는 npm 패키지로 Typescript 프로젝트를 진행하고 있다. 익스프레스에 숙박업소를 추가하고 싶습니다.세션 인터페이스.

예제 클래스:

class User {
    name: string;
    email: string;
    password: string;
}

export = User;

인터페이스 정의에 대한 새 d.ts 파일(express-session.d.ts 편집 안 함):

declare namespace Express {
    interface Session {
        user: User
    }
}

앱.ts

import User = require('./User');

function (req: express.Request, res: express.Response) {
    req.session.user //I want to use it like this.
}

문제는 dd.ts 파일에서 사용자를 알 수 없다는 것입니다. 그러나 사용자 파일 수정이 필요하지도 않고 가져올 수도 없습니다.

세션 인터페이스에 내 클래스를 추가하려면 어떻게 해야 합니까?




파티에 조금 늦었지만 인터페이스를 정의 파일로 가져올 수 있습니다

import { User } from '../models/user';

declare global {
  namespace Express {
    interface Session {
      _user?: User
    }
  }
}



패키지 버전 때문인지 @Vitalii Zurian에서 제공한 답변이 나에게 효과가 없습니다. 세션 데이터를 확장하고 TSC 유형 검사를 전달하려면 인터페이스를 확장해야 합니다.

E.g.

User.ts:

class User {
  name: string = '';
  email: string = '';
  password: string = '';
}

export = User;

app.ts:

import express from 'express';
import User from './User';

declare module 'express-session' {
  interface SessionData {
    user: User;
  }
}

function controller(req: express.Request, res: express.Response) {
  req.session.user;
}

package versions:

"express": "^4.17.1",
"express-session": "^1.17.1",
"@types/express-session": "^1.17.3",
"@types/express": "^4.17.11",
"typescript": "^3.9.7"

result:

enter image description here




For me types.express-session.d.ts:

declare namespace Express {
    interface CustomSessionFields {
        myCustomField: string
    }

    export interface Request {
        session: Session & Partial<SessionData> & CustomSessionFields
    }
}

This answer relates with this post




For those who want to set them in the index.d.ts as an ambient module declaration that will be merged with Express types this is what I have done:

declare namespace Express {
    interface CustomSessionFields {
        myCustomField: string;
    }
    type RequestExpress = import('express-serve-static-core').Request;
    type SessionExpress = import('express-session').Session;
    type SessionDataExpress = import('express-session').SessionData;
    export interface RequestExtended extends RequestExpress {
        session: SessionExpress & Partial<SessionDataExpress> & CustomSessionFields
    }
}



I wonder, why does this not work:

export interface customSession extends SessionData {
  userId: string;
}

When I try to set the session:

req.session.userId = user.user_id;

I get the following error Property 'userId' does not exist on type 'Session & Partial<SessionData>'.


반응형