【问题标题】:Can I omit generic parameters where they are derived from another?我可以省略从另一个派生的泛型参数吗?
【发布时间】:2021-02-20 23:33:15
【问题描述】:

假设我有这样的事情:

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)
}

是否有某种语法可以说“自己解决”?

如果不是,是否有原因导致这种情况?

【问题讨论】:

    标签: typescript generics type-inference


    【解决方案1】:

    你可以assign generic parameter defaults

    type RecordsObject<T, K extends keyof T = keyof T> = {
      primaryKey: K; 
      data: Array<T>; 
    }
    

    Playground

    【讨论】:

    • 嘿,快速提问两者有什么区别。 K 扩展 keyof T = keyof T 和 K = keyof T?好像这就是你想做的所有事情?另外我删除了我愚蠢的答案:-)
    • @Cleanbeans K = keyof T 表示K 绝对可以是任何东西,但如果未设置,它将默认为keyof TK extends keyof T = keyof T 如果未设置也默认为 keyof T,但它限制了 K 的允许值。 K 必须是 T 的键的子集:所有键、一个特定键或几个键的联合。
    • @LindaPaiste 感谢您的指导。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-10-09
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多