Alexander Kim
Alexander Kim

Reputation: 18382

Type 'User | undefined' is not assignable to type 'User'

User controller:

import { User } from './user';

export class UserController {
public static async getuser(ctx: BaseContext) {
  const userRepository: Repository<User> = getManager().getRepository(User);
  const user: User = await userRepository.findOne(ctx.params.id); // error on this line

  if (user) {
    ctx.status = 200;
    ctx.body = user;
  }
}

I get the an error:

error TS2322: Type 'User | undefined' is not assignable to type 'User'. Type 'undefined' is not assignable to type 'User'.

user.ts file (this one i import above):

@Entity('users')
export class User {
  @PrimaryGeneratedColumn()
  id: number | undefined;

  @Column({ type: 'varchar', nullable: true, unique: true })
  username: string | undefined;

  @Column({ type: 'text' })
  password: string | undefined;

  @CreateDateColumn()
  createdAt: Date | undefined;

  @UpdateDateColumn()
  updatedAt: Date | undefined;
}

Can't figure out, on how to fix this.

Upvotes: 4

Views: 6885

Answers (2)

jperl
jperl

Reputation: 5112

As the error says, you're trying to assign a type 'User | undefined' (userRepository.findOne(), expected behavior when passing an id of a user that doesn't exist) to type 'User' (const user).

Since user can also be undefined, you have to change const user: User to const user: User | undefined.

Since there is

if (user) {
    ctx.status = 200;
    ctx.body = user;
  }

right after, I'm guessing user can be undefined.

Upvotes: 5

Richard Haddad
Richard Haddad

Reputation: 1004

userRepository.findOne(ctx.params.id); may be undefined if no user is found. Two solutions:

Treat the search as faillible:

const user: User | undefined = await userRepository.findOne(ctx.params.id);

Or consider that a User will be found:

const user: User = await userRepository.findOne(ctx.params.id)!;

Note that this last solution is a cast, do it only if you are sure that a User will be found (in your case I don't think so).

Upvotes: 3

Related Questions