Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 851
Edward Avatar asked Dec 13 '22 22:12

Edward


1 Answers

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.

like image 98
Nitzan Tomer Avatar answered Dec 28 '22 10:12

Nitzan Tomer