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 define generic typescript type with keyof property?

I would like to have a generic type to use it in some function as an argument, but it is not clear how to define a property that would have strongly typed property names (specificProperties in example code snippet).

type Config<T> = {
    specificProperties: keyof T[],
    data: T[],
}

function doSomething<T>(config: Config<T>) {
    // Some logic here
}

Usage:

type Test = {
    code: string,
    name: string,
}

const config: Config<Test> = {
    specificProperties: [ 'code' ], //Typescript error here
    data: [
        {
            code: 'a',
            name: 'b'
        }
    ]
}

doSomething(config)

Typescript throws an error: Types of property ‘specificProperties’ are incompatible. Type ‘string[]’ is not assignable to type ‘keyof T[]’.

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

It seems Config type should be fixed, but I’m not sure how to do it. Any ideas?

>Solution :

Change keyof T[] to (keyof T)[]. The brackets have a higher priority than the keyof operator.

type Config<T> = {
    specificProperties: (keyof T)[],
    data: T[],
}

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