Home > front end >  Typescript: Infer type of object key
Typescript: Infer type of object key

Time:12-19

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

CodePudding user response:

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

CodePudding user response:

You can simply reuse your User interface

interface User {
    id: string,
    name: string,
    token: string | null,
}

interface Updates<Schema> {
    set: Partial<Schema>;
}

const test: Updates<User> = {
    set: {
        name: null // Type 'null' is not assignable to type 'string | undefined'
    }
}
  • Related