Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: Infer type of object key

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use the type utility Partial<Type> on your existing type directly to make all of its properties optional:

TS Playground

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
  },
};

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading