1

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?

FutureCake
  • 2,614
  • 3
  • 27
  • 70
  • 1
    See the linked questions and their answers for more information. You can use the `KeysMatching` definition in there to write `K extends KeysMatching`, although you might be ultimately happier reversing the constraint to `K extends keyof T, T extends Record`. – jcalz Aug 23 '22 at 18:22

0 Answers0