如何分配A'功能到模型中的变量。打字稿

发布于 2025-02-06 09:13:22 字数 349 浏览 2 评论 0 原文

代码下面:

export class User {

constructor(

  public Id: number,
  public Prefix: string,
  public FirstName: string,
  public LastName: string,
  public MiddleInitial: string,
  public FullName: string = function() {
    return FirstName + ' ' + LastName;
  },
){ }
}

全名变量正在抛出错误,任何帮助/其他方法都将不胜感激。

code below:

export class User {

constructor(

  public Id: number,
  public Prefix: string,
  public FirstName: string,
  public LastName: string,
  public MiddleInitial: string,
  public FullName: string = function() {
    return FirstName + ' ' + LastName;
  },
){ }
}

The fullname variable is throwing an error, any help/other approaches would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

末骤雨初歇 2025-02-13 09:13:24

听起来您只想在班上有一个属性Getter。

类似:

class User {
    constructor(
        public FirstName: string,
        public LastName: string,
    ){}

    get FullName(): string {
        return this.FirstName + ' ' + this.LastName;
    }
}

console.log(new User('A', 'B').FullName) // 'A B'

Playground

It sounds like you just want a property getter on your class.

Something like:

class User {
    constructor(
        public FirstName: string,
        public LastName: string,
    ){}

    get FullName(): string {
        return this.FirstName + ' ' + this.LastName;
    }
}

console.log(new User('A', 'B').FullName) // 'A B'

Playground

っ〆星空下的拥抱 2025-02-13 09:13:23

您声明 fullname 应该期望字符串,但您尝试为其分配功能。
正如您要分配给两个构造函数的组成的fullName值一样身体:

class User {
  public FullName: string;
  
  constructor(
    public Id: number,
    public Prefix: string,
    public FirstName: string,
    public LastName: string,
    public MiddleInitial: string,
  ) { 
    this.FullName = FirstName + ' ' + LastName;
  }
}

You state that FullName should expect string, but you try to assign function to it.
As you want to assign to FullName value that will be a composition of two constructor params, you have to declare FullName as a User class field, and assign value to it in constructor body:

class User {
  public FullName: string;
  
  constructor(
    public Id: number,
    public Prefix: string,
    public FirstName: string,
    public LastName: string,
    public MiddleInitial: string,
  ) { 
    this.FullName = FirstName + ' ' + LastName;
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文