We need to create a function to remove occurrences of an item from an array. It needs to be strongly-typed and work with arrays containing any primitive type. Here’s our attempt:
Copy
function remove<ItemType>(itemToRemove:ItemType, array:Array<ItemType>):ItemType{
The return type has been specified incorrectly. It should be ItemType[] or Array<ItemType>. Alternatively, the return type could be removed to let TypeScript infer this.
4.
We have the following interface which represents a user:
Copy
interfaceUser{
id:any;
name:string;
email:string
}
How can we improve this by removing the any type on the id property and letting the consumer of the interface supply its type?
Copy
interfaceUser{
id:string|number;
name:string;
email:string
}
Copy
interface<UserIdType>User{
id:UserIdType;
name:string;
email:string
}
Copy
interfaceUser<UserIdType>{
id:UserIdType;
name:string;
email:string
}
5.
We need to extend the generic list class we created in the last lesson. As a reminder, here’s the class:
Copy
classList<ItemType>{
private items:ItemType[]=[];
add(item: ItemType){
this.items.push(item);
}
}
We need to add a method called getNth which returns the array item at the nth position in the list. How could we implement this?
Copy
getNth(n: number){
returnthis.items[n];
}
Copy
getNth(n:number):ItemType[]{
returnthis.items[n];
}
Copy
getNth(n: ItemType){
returnthis.items[n];
}
6.
We have a function below which outputs the name property of an object to the console. How can we use generics to make this more strongly-typed?
Copy
functionlogName(object: any){
console.log("My name is "+ object.name);
}
Copy
function logName<T>(object:T){
console.log("My name is "+ object.name);
}
It isn't possible to make the function more strongly-typed.
Copy
function logName<Textends{name:string}>(object:T){