Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptGenerics Interface in typescript

Generics Interface in typescript

“A major part of software engineering is building components that not only have well-defined and consistent APIs but are also reusable. ” This sentence is in the official documentation we would start with. There are languages that are strong in static typing & others that are weak in dynamic typing. At this point, Typescript has shown to have well-defined APIs with those languages that are weak in dynamic typing. 

Why generics?

For every technology approach, we are about to learn we should know why this approach has been created and added, so think about it. We have a function that takes a number and do some operations finally returns a number, and we need a function that takes a string and do the same operations and returns a string, and this is solving the problem of the “any” type and able to capture the type.

Working with arrays:

You just need to add Type before brackets like this, I would take the array example to work, as the examples of interface would treat, in the next example we will create a function that takes an array with a certain type and return the array.

Example 1:

Typescript




// This function takes array of any type that
// you determine while calling the function
function getArray<Type>(array: Type[]) {
 
    // Do some operations
    return array;
}
 
// We call the function
const arrayOfStrings = getArray < string > ([
    "John", "Sam", "Arnold"])


Output:

 

We can also add more than a generic type, I will create a function that takes two arguments  with undefined types T & V and return their values

Example 2:

Typescript




// Here we can define two generics type
// with any name you choose
function getInfo<T,V>(name:T,id:V){
    return `My name is ${name} and my id is ${id}`;
}
 
console.log(getInfo("John",123));


Output:

 

 

Generics With interface: First, what is the interface in typescript & what is the approach we follow?

Simply, we can say the interface is the schema for an object you create, it defines the properties and their types, and we can define an interface with the interface keyword here is the syntax in the next example we determine an interface and type in it its properties and the schema should the object follow.

Example 1:

Typescript




interface props {
    // Here we define properties & and their types
    id: number,
    name: string,
}


And now we can define the generic type by adding <T>  in the next example I will create an interface and make the object person applies its properties and passing type of  the array

Javascript




// Here is the interface and define
// generic type with <T>
interface props<T> {
    names: T[];
    id: number
}
 
// Here we make the object apply to the
// schema we define in the interface
let person : props<string> =
    {names:["first name","last name"],id:123}
 
console.log(person);


Output:

 

We can also specify What T type should contain a certain property by using extends keyword in the next example we define an interface that takes the T type that should have the id property, secondly, create an interface that has the id property and pass it as a type for the props  interface & make customData object apply its properties

Example 2:

Typescript




interface props<T extends {id:number}>{
    data:T[]
}
 
// Here the object must have id property
interface objectProps{
    id:number,
    name:string,
    SN:number
}
 
// Passing objectProps as a type containing id
let customData : props<objectProps> =
    {data:[{id:123,name:"John",SN:4324342}]}
 
console.log(customData);


Output:

 

In the previous example, if the Object “customData” doesn’t have an “id”, it will be an error. So by the “extends” keyword “customData” object is forced to contain the “id” property, this technique is called “Constraints generics”.

We can also do this in the next example. Create an interface containing the id property then create a function that takes an array of type T that extends the props interface and return the array.

Example 3:

Typescript




interface props {
    id: number
}
 
// This function returns array of objects
// that must have id property
function getInfo <T extends props>(data:T[]):T[]{
    return data;
}
 
console.log(getInfo([{id:123,name:"John"},
    {id:345,name:"debruyne"},
    {id:789,name:"sam"}]));


Output: 

 

The advantage of generics?

The advantage starts to show in this question: Can we replace generics with any type? Technically no, we can’t, when we are using any as generic, we almost don’t know what are the type function args take and what it returns, we lose information about this function, and as official documentation says: by generics, we can capture the type of functions and variables, by generics we keep and increase type safety.

The disadvantage of generics in the interface?

We can say that you write more code and add more specifications to our code which make the code messy sometimes

Applications We can use typescript by installing typescript through npm and adding it to any javascript application, it makes testing application easier and add a strong static typing feature for javascript, and through time compilation error if we write the wrong type of the property

RELATED ARTICLES

Most Popular

Recent Comments