how to define value type when using keyof (typescript)

Viewed 27

I have an interface like so:

interface SearchListProps<T extends object, K extends keyof T> {
    data: T[];
    sort_and_filter_key: K;
}

In this interface i have the property sort_and_filter_key which can only be a key of the supplied generic object. But this still allows for the possibility that the value of this key can be anything. But i would like to limit the options for this value to only be strings.

So the following would be valid:

interface Test {
    a: string, 
    b: number,
    c: object
}

const objectB: SearchListProps<Test, keyof Test> = {
    data: [{ a: "as", b: 1, c: {} }],
    sort_and_filter_key: "a", // true
}

Since in the example above the value of sort_and_filter_key is a string

and this would be invalid:

const objectA: SearchListProps<Test, keyof Test> = {
    data: [{ a: "as", b: 1, c: {} }],
    sort_and_filter_key: "b", // false
}

Since here the value of sort_and_filter_key is a number.

Is this possible with a generic definition?

0 Answers
Related