Currently, the indexed access type returns a union of all of the types in the object.
How do I restrict the indexed type to the type of the key?
interface User {
id: string,
name: string,
age: number,
token: string | null,
}
interface Updates<Schema> {
set: Partial<Record<keyof Schema, Schema[keyof Schema]>;
}
const test: Updates<User> = {
set: {
name: 1 // This should not work
}
}
>Solution :
You can use the type utility Partial<Type> on your existing type directly to make all of its properties optional:
interface User {
id: string;
name: string;
token: string | null;
}
interface Updates<T> {
set: Partial<T>;
}
const test: Updates<User> = {
set: {
name: /* still needs a value */,
//^? (property) name?: string
},
};