Search code examples
typescripttypescript-generics

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[]'.

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