Issue
I got this Typescript example from this tutorial
interface Logable {
log: () => void;
}
function logItems<T extends Logable>(items: T[]): void {
items.forEach(item => item.log());
}
And I'd like to know if, in this case, there's any difference between using the generic constraint or just using logItems(items: Logable[])
It seems like, if you don't need a more complex constraint, it's simpler to just specify the type of the parameter.
Am I right?
Solution
You are right in thinking that it does not really make a difference. In a broader sense, as long as you are not using generics to model relations between parameters or for the return type, you might not need the generic type in the first place.
But there is a subtle difference. If we use the generic function, it is perfectly fine to pass an array of objects of any shape as long as the constraint is fulfilled.
function logItems<T extends Logable>(items: T[]): void {
items.forEach(item => item.log());
}
logItems([
{ log: () => {} },
{ a: "123", log: () => {} }
])
Extra properties are allowed in this case.
Something different happens when we don't use a generic type.
function logItems2(items: Logable[]): void {}
logItems2([
{ log: () => {} },
{ a: "123", log: () => {} }
// ^^^^^^^^ Error: Object literal may only specify known properties, and 'a' does not exist in type 'Logable'
])
Since there are extra checks for excess properties when you pass an object literal to the function, there is a compiler error.
But you could still pass the array as a variable to the function.
const arr = [
{ log: () => {} },
{ a: "123", log: () => {} }
]
logItems2(arr)
Answered By - Tobias S.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.