TypeScript-Node-Starter icon indicating copy to clipboard operation
TypeScript-Node-Starter copied to clipboard

Error when build: Property 'xxx' does not exist on type 'User'.

Open nguyentranchung opened this issue 5 years ago • 5 comments

image

nguyentranchung avatar Aug 22 '19 23:08 nguyentranchung

Seems like the problem is an update on the @types/passport declaration: https://github.com/DefinitelyTyped/DefinitelyTyped/commit/91c229dbdb653dbf0da91992f525905893cbeb91#comments

I fixed it by augmenting with a file in /src/types using the following

import { UserDocument } from '../models/User'

declare global {
    namespace Express {
        interface User extends UserDocument {}
    }
}

dweirich avatar Aug 28 '19 05:08 dweirich

Thanks for this.

chase-oneill avatar Sep 01 '19 06:09 chase-oneill

Let me know if that works: Thanks!

import express from 'express';
import { UserDocument } from '../models/User';

declare module 'express' {
  export interface User extends UserDocument {}
  export interface Request {
    user?: User;
  }
}
``

peterblazejewicz avatar Sep 03 '19 18:09 peterblazejewicz

In case you get the Duplicate Key Error, make sure you use interface not type even if the linter complains. make sure to disable it:

// eslint-disable-next-line @typescript-eslint/no-unused-vars
import * as MongoUserSchema from '../../src/mongo/models/User';

declare global {
  namespace Express {
    // eslint-disable-next-line @typescript-eslint/no-empty-interface
    interface User extends MongoUserSchema.User {}
  }
}

TypeScript Rules!

akoushke avatar May 03 '20 08:05 akoushke

This is the solution that worked for me:

export {};

declare global {
  namespace Express {
    interface User {
      username: string;
      id?: string;
      profile?: any;
      // Add whatever you're missing
    }
  }
}

You can place this within a .d.ts file that is within scope of your project. It'll stop TypeScript from complaining, but the usage of any here is iffy at best.

acerspyro avatar Jun 08 '20 02:06 acerspyro