Optional Properties in TypeScript

What is Optional Properties in TypeScript?

We can specify optional properties on interfaces and the property may be present or missing in the object.


In the below example, the address property is optional on the following “User” interface.

Example as,
//USER INTERFACE 
interface User {
    name: string;
    age: number;
    address?: string //Optional
}

//FUNCTION USING USER INTERFACE 
let userInfo = function(user: User) {
   let info = "Hello, " + user.name + " Your Age is - " + user.age + " and Address is -" + user.address;

   return info;
}

//USER INFO JSON OBJECT
let info = {
    name: "Anil",
    age: 30
};

//RESULT
console.log(userInfo(info));

Stayed Informed – Learn Angular 2 with TypeScript

I hope you are enjoying with this post! Please share with you friends. Thank you!!
ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.