假设我有这样的东西:
type RecordsObject<T, K extends keyof T> = {
primaryKey: K;
data: Array<T>;
}
类型在哪里
K
必须从类型派生
T
.
RecordsObject
TypeScript坚持要我定义这两个泛型参数。
例如:
type Student = {
id: string;
name: string;
}
function processStudentRecords(records: RecordsObject<Student, keyof Student> ) {
const allPrimaryKeys = records.data.map(v => v[records.primaryKey]);
}
问题是-我不应该在这里声明第二个泛型参数-我看不出我在这里添加了任何附加信息。
但如果我不说,我会得到:
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)
}
有什么语法可以说“自己解决这个问题”吗?
如果不是的话,有没有理由这样?