Home > Enterprise >  Use a variable as as key of an interface to get the typeof
Use a variable as as key of an interface to get the typeof

Time:12-18

Is it possible to use a variable to get the typeof a key in a interface?

For example:

interface DbSchema {
  jobs: {
    jobId: number;
    jobName: string;
  }
  users: {
    userId: number;
    userName: string;
  }
}

// I know we can do this:
type JobsType = DbSchema["jobs"];

// Is there a way to do this:
const str = "jobs";
type JobsType = DbSchema[str];

CodePudding user response:

interface DbSchema {
  jobs: {
    jobId: number;
    jobName: string;
  }
  users: {
    userId: number;
    userName: string;
  }
}

const str = "jobs";
type JobsType = DbSchema[typeof str];

![enter image description here

playground

const already narrow the type for you, you just need typeof

CodePudding user response:

You can do it, using keyof and typeof keywords like this:

const s:keyof DbSchema = "jobs"
type JobsType = DbSchema[typeof s];

You should guarantee that type of s is keyof DbSchema and also when you want to get the type of one of the DbSchema properties you have to use typeof s.


But I think the more reasonable and cleaner approach is using a generic type. You can define a type like this :

type DbSchemaPropertyType<T extends keyof DbSchema> = DbSchema[T];

And use it easily :

const job:DbSchemaPropertyType<"jobs"> = {
    jobId: 1,
    jobName: "student"
}
  • Related