首页 文章

TypeScript属性的默认值

提问于
浏览
2

我在TypeScript中定义了一个接口,如下所示:

export interface User {
    id?: number;
    name?: string;
    logoUrl?: File;   
    emailUserName?: string;
    emailPassword?: string;
}

使用User,我将其绑定到Angular html输入 . 如果我在输入中输入任何内容,则用户对象将包含值,但是,如果我不输入,则名称之类的属性将取消定义 . 如果我没有为name输入字符串,我怎么能得到名称的空值 . 更新

<div *ngIf="hero">
<h2>{{hero.name}} details!</h2>
<div>
<label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name" />
<input [(ngModel)]="hero.location" placeholder="location" />
</div>
<button (click)="goBack()">Back</button>
</div> 
//model
    export class Hero {
    private _location:string="test";
    constructor(){
    console.log(this._location);
    this.location=this._location;
    }
    public id: number;
    public name: string;
    public location:string;
    } 

goBack(): void {
console.log(this.hero);
// this.hero=new Hero();
// console.log(this.hero);
//this.location.back();
}
}

如果我没有在输入中输入任何值,goBack将输出没有位置属性的英雄 .

3 回答

  • 2

    您可以为 User 而不是接口创建一个类,并在getter中执行以下操作:

    class User {
        private _name: string;
        ...
    
        get name() {
            return this._name || "";
        }
    }
    

    甚至在构造函数中为 this._name 分配一个空字符串 .

    如果您更喜欢使用界面,则可以使用以下功能:

    function normalizeUser(user: User) {
        return Object.assign({ name: "" }, user);
    }
    

    编辑

    是的,这是如何在ctor中设置默认值:

    class User {
        private static DEFAULT_NAME = "";
    
        public name: string;
        ...
    
        constructor() {
            this.name = User.DEFAULT_NAME;
        }
    }
    

    至于 get name() 部分,它是一个访问者,所以如果你使用它,那么:

    let a = new User();
    console.log(a.name);
    

    More on accessors .

  • 0

    你也可以使用这个简写:

    class User {
      constructor(public id: number = -1,
        public name: string = '',
        public logoUrl: File = 'defaultLogo.png' ,
        public emailUserName: string = ''
        public emailPassword: string = '') {}
    }
    
  • 1

    你做不好吗?

    this.user.name?this.user.name:"";
    

相关问题