Typescript Generic Function Constraint
Consider the following function which returns the longer of two values.
function longest(a, b) {
if (a.length >= b.length) {
return a;
} else {
return b;
}
}
const longerArray = longest([1, 2], [1, 2, 3]);
console.log(longerArray); // [1, 2, 3]
const longerString = longest("alice", "bob");
console.log(longerString); // alice
const notOK = longest(10, 100);
console.log(notOK); // 100Note in Javascript, there is no error for the third case even number has no length property.
If we want to show error when the input has no length property, we can add type to the above function and use generics to constrain the Type to be a data type with length property that’s a number.
function longest<Type extends { length: number }>(a: Type, b: Type) {
if (a.length >= b.length) {
return a;
} else {
return b;
}
}
// longerArray is of type 'number[]'
const longerArray = longest([1, 2], [1, 2, 3]);
console.log(longerArray);
// longerString is of type 'alice' | 'bob'
const longerString = longest("alice", "bob");
console.log(longerString);
// Error! Numbers don't have a 'length' property
const notOK = longest(10, 100); // Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.
Reference
https://www.typescriptlang.org/docs/handbook/2/functions.html#constraints