简体   繁体   中英

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.

So the class will have a function that is typed to return a 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

{
   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.

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.

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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