代码之家  ›  专栏  ›  技术社区  ›  dwjohnston

如果泛型参数是从另一个派生的,我可以省略它们吗?

  •  0
  • dwjohnston  · 技术社区  · 5 年前

    假设我有这样的东西:

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

    有什么语法可以说“自己解决这个问题”吗?

    如果不是的话,有没有理由这样?

    2 回复  |  直到 5 年前
        1
  •  3
  •   dwjohnston    5 年前

    你可以 assign generic parameter defaults .

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

    Playground