简体   繁体   中英

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?

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

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