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.
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.