Imagine having a scenario like this:
type RecordsObject<T, K extends keyof T> = {
primaryKey: K;
data: Array<T>;
}
where the type K
is always derived from the type T
.
Oftentimes, when I try to declare something as of type RecordsObject
, TypeScript requires that I specify both generic parameters.
For instance:
type Student = {
id: string;
name: string;
}
function processStudentRecords(records: RecordsObject<Student, keyof Student> ) {
const allPrimaryKeys = records.data.map(v => v[records.primaryKey]);
}
The issue here is that I believe specifying the second generic parameter in this case is unnecessary and doesn't add any extra information.
However, if I omit it, I encounter the following error:
function processStudentRecords(records: RecordsObject<Student> ) { //Generic type 'RecordsObject' requires 2 type argument(s).(2314)
const allPrimaryKeys = records.data.map(v => v[records.primaryKey]); //Parameter 'v' implicitly has an 'any' type.(7006)
}
Is there a way to instruct TypeScript to infer the missing parameter on its own?
If not, what could be the rationale behind this requirement?