简体   繁体   English

打字稿泛型定义依赖性

[英]typescript generics definition dependency

I want to define a generic class like Table <t> where T is the interface of the data structure that the table will be bound to. 我想定义一个通用类,例如Table <t> ,其中T是表将要绑定到的数据结构的接口。

So the class will have a function that is typed to return a Promise <t> . 因此,该类将具有键入返回Promise <t>的函数。

But I also need to be able to pass in as props, a list of columns with their labels, whether they are sortable etc. 但是我还需要能够传递道具,带有标签的列列表,是否可排序等。

This list of columns needs to be tightly coupled to the definition of <t> ie if my definition of <t> is 此列列表需要与<t>的定义紧密结合,即,如果我对<t>定义是

{
   id: string,
   description: string,
   createdDate: Date
}

then the list of columns that need putting in must be a list of 3 columns with the keys for each of those being id , description and createdDate respectively. 那么需要放入的列的列表必须是3列的列表,且每个列的键分别为iddescriptioncreatedDate

How can I define that list of columns using Typescript and T so that if the columns you send in don't match up with the definition of T then compilation fails. 如何使用Typescript和T定义该列列表,以便如果您发送的列与T的定义不匹配,则编译将失败。

Thanks 谢谢

The simplest solution is not to use a list. 最简单的解决方案是不使用列表。 An object literal is a better choice since it already checks no duplicates occur and mapped types can easily be used to create a new type base on T that will have the same keys but with a different type : 对象文字是一个更好的选择,因为它已经检查没有重复发生,并且映射类型可以轻松地用于基于T创建具有相同键但具有不同类型的新类型:

interface Columns {
    id: string,
    description: string,
    createdDate: Date
}

interface IColumnDescription {
    name: string;
    // other props
}

class Table<T> {
    constructor(columns: Record<keyof T, IColumnDescription>) {

    }
}

new Table<Columns>({
    createdDate: { name: "Created Date" },
    description: { name: "Description" },
    id: { name: "Id" },
})

We can also probably do it with a list, but just starting to look at how there are issues. 我们也可以用一个列表来做,但是只是开始看看有什么问题。 We would probably need a static method to create the table since we would need extra type parameters to get the type of the column list. 我们可能需要一个静态方法来创建表,因为我们需要额外的类型参数来获取列列表的类型。

Also code completion will probably work better with the object literal solution which is important for dev experience. 同样,代码完成可能会更好地与对象字面量解决方案一起使用,这对开发人员的经验很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM