开发者

Declare a typesafe typesafe const object in typescript

开发者 https://www.devze.com 2022-12-07 18:58 出处:网络
I am working with Prisma which generates query return types based on the structure of the parameter passed into the invocation of the query.

I am working with Prisma which generates query return types based on the structure of the parameter passed into the invocation of the query.

For example:

const response = await Prisma.user.findUnique({ 
    where: { name: 'A name' },
    select: { name: true, email: true }
);

Will query the user table for a user with the name 'A name' and return an object with the name开发者_Python百科 and email properties.

Prisma exports a UserSelect type which is defined to be something like

export type UserSelect {
  name?: boolean
  email?: boolean
  ...
}

Whilst editing the parameter object inline, vscode is able to provide full intellisense of parameters, however, I have several places where I am querying the same property selections so I wanted to try and pull out some reusable selections.

export const DefaultUserSelection = {
  name: true,
  email: true,
} as const

This works and Prisma still infers the correct type information for the return type of the query, however, because typescript doesn't know what type the selection is supposed to satisfy, there is no intellisense.

Declaring DefaultUserSelection: Prisma.UserSelection breaks the type inference of the query.

Is it possible to convey that the object I am authoring should be a const assertion, AND satisfy the Prisma.UserSelection type? I tried {} as Prisma.UserSelection as const but typescript complains that a const assertion can only be applied to a literal object.

I could just author the object as as Prisma.UserSelection, then swap it to as const when I'm done, but it's a bit clunky and would make future changes harder.


The solution is the new (ts 4.9) satisfies keyword.

export const DefaultUserSelection = {
  name: true,
  email: true,
} satisfies Prisma.UserSelect;

This provides full intellisense whilst defining the properties on the object, whilst maintaining the most narrow as const type.

In VS Code I had to ensure it was using my local project ts version (4.9.3) by specifying typescript.tsdk in my workspace settings.json file.

0

精彩评论

暂无评论...
验证码 换一张
取 消