Typescript create interface instance

Typescript create interface instance

Last updated: Jan 23, 2023
Reading time · 3 min

banner

# Create an Object based on an Interface in TypeScript

To create an object based on an interface, declare the object’s type to be the interface.

The object has to conform to the property names and the type of the values in the interface, otherwise, the type checker throws an error.

Copied!
interface Employee salary: number; name: string; address: country: string; city: string; >; > // ✅ Declare directly const obj: Employee = salary: 100, name: 'Bobby Hadz', address: country: 'Chile', city: 'Santiago', >, >;

Here is an example that uses a type assertion instead.

Copied!
interface Employee salary: number; name: string; address: country: string; city: string; >; > // ✅ Using type assertion const obj = > as Employee; obj.name = 'Bobby Hadz'; obj.salary = 200;

The first example declares the object to be of type Employee directly.

When using this approach, you have to declare the object to have all of the necessary properties of the interface.

# Using default values when declaring the object

You could use default values if you don’t have all of the properties in advance.

Copied!
interface Employee salary: number; name: string; address: country: string; city: string; >; > // ✅ Declare directly const obj1: Employee = salary: 0, name: '', address: country: '', city: '', >, >;

However, you can’t omit any of the required properties that are defined on the interface.

# Create an Object based on an Interface using a type assertion

You can also use a type assertion to set the object’s type to the type specified in the interface.

Copied!
interface Employee salary: number; name: string; address: country: string; city: string; >; > const obj = > as Employee; // 👈️ type assertion obj.name = 'Bobby Hadz'; obj.salary = 200;

Type assertions are used when we have information about the type of a value that TypeScript can’t know about.

When using them, we effectively tell TypeScript that value X will be of type Y and not to worry about it. This could cause runtime errors if we are wrong.

In the example, we tell TypeScript that the obj variable will be of type Employee , so it shouldn’t worry about it.

However, note that we don’t have to set all of the required properties on the object.

For example, the address property is required in the Employee interface, but we didn’t get an error when we omitted it.

This is because when we used the as Employee syntax, we told TypeScript that the obj variable already has all of the properties an Employee has.

If you need to create a type from an object’s keys or values, click on the following link.

# Marking properties as optional

If you want to mark a property in an interface as optional, you can use a question mark.

Copied!
interface Employee salary?: number; // 👈️ optional name?: string; // 👈️ optional address: country: string; city: string; >; > const obj1: Employee = address: country: 'Chile', city: 'Santiago', >, >;

When a property is marked as optional, we aren’t required to set it when initializing the object of the specific type.

Optional properties can either be of the specified type or be undefined .

Even though TypeScript doesn’t require us to set the salary and name properties when creating the object, it still checks that any properties added later on conform to the Employee interface.

# Create an Object based on an Interface using a custom function

An alternative way to create an object based on an interface is to define an initializer function.

Copied!
interface Employee salary: number; name: string; address: country: string; city: string; >; > function createEmployee(options?: PartialEmployee>): Employee const defaults = salary: 0, name: '', address: country: '', city: '', >, >; return . defaults, . options, >; > const obj: Employee = createEmployee( name: 'Bobby Hadz' >); // 👇️ > console.log(obj);

The createEmployee function can be called with an options object or no parameters at all.

The function defines the default values for the Employee interface and uses the spread syntax (. ) to unpack the defaults before unpacking any of the user-provided values.

We used the Partial utility type to set all of the properties in the Employee interface to optional in the function’s parameter.

Any of the values the function is passed will override the default values.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Create an Object From Interface in TypeScript

Create an Object From Interface in TypeScript

  1. Assign All Fields in the Created Object in TypeScript
  2. Use the as Keyword to Set an Empty Object in TypeScript
  3. Use the as Keyword to Set Only the Required Attributes in TypeScript
  4. Use the Partial , Omit , and Pick Types to Create an Object in TypeScript
  5. Use the ? Operator to Make Attributes in the Interface Optional in TypeScript

Interfaces in TypeScript provide a construct for strict typing support compared to plain JavaScript. The user may design interfaces or be present in a third-party library imported by the user.

Most of the time, the user wants to create an object based on the interface definition provided in the third-party library to access the methods and functionality provided by the third-party library.

This article will focus on creating an object from an interface definition.

Assign All Fields in the Created Object in TypeScript

All the properties associated with the interface definition can be directly assigned to the newly created object. The following code segment demonstrates this.

interface Animal   legs : number ;  eyes : number ;  name : string ;  wild : boolean ; >;  const dog : Animal =   legs : 4,  eyes : 2,  name : 'Dog',  wild : false >; 

The properties can now be accessed from the object like dog.name or dog.wild .

Use the as Keyword to Set an Empty Object in TypeScript

An empty object can be initialized using the as keyword, whose attributes can be set later. The following code segment demonstrates this.

interface Animal   legs : number ;  eyes : number ;  name : string ;  wild : boolean ; >;  const dog : Animal = <> as Animal;  dog.legs = 4; dog.name = "Dog"; console.log(dog); 

Thus an empty object was initialized of the type Animal , and the attributes legs and name were set. When the object was printed, it only showed the set attributes.

Use the as Keyword to Set Only the Required Attributes in TypeScript

The required attributes can be set directly using the as keyword. The as keyword forces the compiler to recognize the object is of a certain type even if all the fields in the object have not been set.

interface Animal   legs : number ;  eyes : number ;  name : string ;  wild : boolean ; >;  const dog : Animal =   legs : 4,  name : 'Dog', > as Animal; 

Use the Partial , Omit , and Pick Types to Create an Object in TypeScript

The Partial type is used to make all attributes of an interface optional. The Pick type is used when only certain interface attributes are required to create the object.

The Omit type is used as the inverse of the Pick type — to remove certain attributes from the interface while keeping all the other attributes as required.

interface Animal   legs : number ;  eyes : number ;  name : string ;  wild : boolean ; >;  const dogOnlyWithName : PickAnimal, 'name'> =   name : "Dog" >;  const dogWithoutWildFlagAndEyes : OmitAnimal, "wild" | "eyes"> =   legs : 4,  name : "Dog" >  const dogWithAllOptionalTypes : PartialAnimal> =   eyes: 2 >; 

Use the ? Operator to Make Attributes in the Interface Optional in TypeScript

Some of the attributes in the interface can be marked optional by the ? operator. This is a viable option in the case of user-defined interfaces but cannot be implemented in the case of interfaces imported from third-party libraries.

interface Animal   legs : number ;  eyes? : number ;  name : string ;  wild? : boolean ; >;  const dog : Animal =   legs : 4,  name : 'Dog' >; 

Shuvayan is a professional software developer with an avid interest in all kinds of technology and programming languages. He loves all kinds of problem solving and writing about his experiences.

Related Article — TypeScript Interface

Источник

Читайте также:  Java server socket options
Оцените статью