TypeScript: Include package types in `keyof`

Viewed 71

I've been working on a previous problem where I think the issue now boils down to the fact that the types are not included in the keyof operator. See the following example:

// my-module.ts
export const someValue = 1
export const anotherValue = 2
export type MyType = "a" | "b" | "c"


// other-file.ts
import * as pkg from "./my-module";

type ValidOptions = {
  [key in keyof typeof pkg]: typeof pkg[key]
}

Using VSCode's IntelliSense shows that ValidOptions only includes the variables, and not MyType.

After discovering this, it seems perfectly reasonable to do so, but I'm wondering if there is a way to include the types as well. I need the types to be able to do something like:

import * as pkg from "@prisma/client";

type Schemas = {
  [K in keyof typeof pkg & pkg.Prisma.ModelName]: typeof pkg[K];
};

Which is a map containing all the available models. I'm trying to do this because Prisma does not export a type like:

type Schemas = User | Log | ...

That lists the models out for me, and I would prefer not having to explicitly define the models myself if possible.


Edit: A more concrete example:

export const someValue = 1
export const anotherValue = 2
export type User = {
  id: number;
  username: string;
  password: string;
};
export type Log = {
  id: number;
  username: string;
  password: string;
};
// Not sure why it is defined like this in the declaration for prisma
export const ModelName: {
  User: "User";
  Log: "Log";
};

export type ModelName = typeof ModelName[keyof typeof ModelName];

Where, using the same other-file.ts as above, the types User and Log are not included in the definition of the ValidOptions type. ValidOptions should only contain User and Log which is why I tried:

type Schemas = {
  [K in keyof typeof pkg & pkg.Prisma.ModelName]: typeof pkg[K];
};
0 Answers
Related