我正在尝试约束键,因此它只能引用 TItem 的数字或日期键。
public static indexOfMin<TItem extends object | number | Date>(array: Array<TItem>, key?: keyof TItem): number {
let min: number = Number.MIN_SAFE_INTEGER;
let index: number = -1;
const length = array.length;
for (let i = 0; i < length; i++) {
const value = Number(isNullOrUndefined(key) ? array[i] : array[i][key]);
if (value < min) {
min = value;
index = i;
}
}
return index;
}
interface IPerson {
name: string;
age: number;
dob: Date;
}
indexOfMin(new Array<IPerson>(), 'name'); // error as name is string.
indexOfMin(new Array<IPerson>(), 'age'); // ok are age is number.
indexOfMin(new Array<IPerson>(), 'dob'); // ok are age is Date.