Home > Software engineering >  How to define generic typescript type with keyof property?
How to define generic typescript type with keyof property?

Time:05-18

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?

CodePudding user response:

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

  • Related