如何访问通用类型的属性?

时间:2019-05-21 09:28:27

标签: typescript linq

作为学校项目的一部分,我正在用打字稿构建类型安全的LINQ框架,项目描述在此处:https://github.com/hogeschool/Software-Engineering-Minor/blob/master/Projects/project2%20-%20mini%20typesafe%20LINQ%20to%20SQL.md

到目前为止,我已经实现了Select,现在我在Include。我有类型签名,但是现在是方法的实现。

想法是该代码应返回以下类型:

students.Select("name").Select("age").Include("Grades", q => q.Select("grade", "courseId"))

返回类型:

{
name: string
age: number
Grades: List<{grade: number, courseId: string}> // Or Array, doesn't matter in this case
}

方法签名如下:

Include: <R extends Filter<T, List<any>>, P extends keyof ListType<T[R]>>(
        record: R,
        q: (_: Table<ListType<T[R]>, Unit>) => Table<Omit<ListType<T[R]>, P>, Pick<ListType<T[R]>, P>>
    ) =>
        Table<Omit<T, R>, U & { [r in R]: List<Pick<ListType<T[R]>, P>> }>

我写下了步骤以产生正确的返回类型:

type R = Filter<Student, List<any>>
type P = "grade"
let a: R = "Grades"
let query1: (_: Table<ListType<Student[R]>, Unit>) => Table<Omit<ListType<Student[R]>, P>, Pick<ListType<Student[R]>, P>> = (q) => q.Select("grade")

// Is the same as bind or flatMap as some of you would like to call it;)
let res1 = join_list(students.map(student => query1(createTable(student[a])).toList() ))
// or...
let res2 = students.bind(student => query1(createTable(student[a])).toList() )
// The type of res1 and res2 is List<{grade: number}>

let included_students = students.map(student => {
    let without_grades = omitOne(student, a)

    return {[a]: res2}
})

问题是如何将其泛化,使其可以与泛型一起使用?

因为当我尝试在方法中重现此错误时,出现以下错误:

  

'T [R]'类型的参数不能分配给'List>'类型的参数。

使用以下代码行:

this.data.First.bind(entry => q(createTable(entry[record])).toList() )

0 个答案:

没有答案