键入“用户|未定义"不能分配给“用户"类型 [英] Type 'User | undefined' is not assignable to type 'User'

查看:55
本文介绍了键入“用户|未定义"不能分配给“用户"类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户控制器:

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;
  }
}

我得到一个错误:

错误TS2322:键入用户|未定义"无法分配给用户"类型.无法将未定义"类型分配给用户"类型.

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

user.ts文件(我在上面导入了这个文件):

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.

推荐答案

如错误所示,您正在尝试分配类型'User |undefined"(userRepository.findOne(),传递不存在的用户ID时的预期行为)键入"User"(常量用户).

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

由于还可以定义用户,因此必须将 const user:User 更改为 const user:User |.未定义.

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

因为有

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

紧接着,我猜用户可能是不确定的.

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

这篇关于键入“用户|未定义"不能分配给“用户"类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆