I have this type:
type DropdownProps<T> = {
data: T[],
id: keyof T,
};
The problem is that if I now try to use id
it will have the any
. I need to make sure that id
is either type number
or string
.
Basically, I want to pass an array of objects and one of the object's keys. That key should return a value of the type string
or number
.
I don't want to require the key to be called id
, but if that's necessary to make it work it would be fine.
CodePudding user response:
Intersect it with the types you want:
type DropdownProps<T> = {
data: T[],
id: keyof T & (string | number),
};
CodePudding user response:
// to limit T type keys:
type DropdownProps<
T extends Record<string | number, any>,
K extends keyof T
> = {
data: T[],
myId: K,
};
// to limit picked keys
type DropdownProps<
T extends Record<any, any>,
K extends (keyof T) & (string | number)
> = {
data: T[],
myId: K,
};