Can someone assist me with TypeScript generics? I am wondering how to access the T["value"] field within the ActionAdd
interface.
type UserValue = { username: string; };
interface User {
id: number;
value: UserValue;
}
interface ActionAdd<T = unknown> {
type: "ADD";
value: T["value"]; // Type '"value"' cannot be used to index type 'T'.
}
type UserAction = ActionAdd<User>;
The T
object will always contain a { value }
key, but it does not necessarily have to be of type unknown
- however, the object will also have other keys.
I have already attempted:
interface ActionAdd<T, K extends keyof T> {
type: "ADD";
value: T[K];
}
type UserAction = ActionAdd<User, "value">;
OR:
interface ActionAdd<T = unknown> {
type: "ADD";
value: T extends { value: infer V } ? V : never;
}
type UserAction = ActionAdd<User>;