简体   繁体   中英

TypeScript Default Value for property

I have defined an Interface in TypeScript like below:

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

With User, I bind it to Angular html input. If I enter anything in the input, the User Object will contains the value, But, If I do not enter, the property like name will be undefine. How could I get empty value for name if I do not enter string for name. Update

<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 will output hero without location property if I do not enter any value for it in input.

You can have a class for User instead of an interface, and in the getter do something like:

class User {
    private _name: string;
    ...

    get name() {
        return this._name || "";
    }
}

or even assign an empty string to this._name in the constructor.

If you prefer to use an interface you can have a function that does that:

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

Edit

Yes, here's how to set the default value in the ctor:

class User {
    private static DEFAULT_NAME = "";

    public name: string;
    ...

    constructor() {
        this.name = User.DEFAULT_NAME;
    }
}

As for the get name() part, it's an accessor, so if you use it then:

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

More on accessors .

Also you can use this shorthand:

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

你做不好吗?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM