Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign same type as one of the type member?

For example, I have this code:

interface DbType {
    id: string,
}

interface RowType extends DbType {
    name: string
}

class db<T> { // How do I put that it must be an extension of DbType?

    insert(item: T) { }
    delete(id: [typeof id]) { } // What should I put here?
}

I want to limit the parameter type, also the T type, to be corresponds to DbType.

So when I do new db<RowType>() I want the delete method would accept the same type as DbType.id

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to do that?

>Solution :

I think what you’re looking for is a simple generic constraint and an Indexed Access type for the delete parameter.

interface DbType {
  id: string;
}

interface RowType extends DbType {
  name: string;
}

class DB<T extends DbType> {
  insert(item: T) {}
  delete(id: T["id"]) {} 
}

TypeScript Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading