Help understanding this line of JS/TS

const globalForPrisma = global as unknown as { prisma: PrismaClient }; how is the object being casted to unknown but also to "prisma" (which itself is of type PrismaClient)? What is likely the purpose of this?
3 Replies
Ryan
RyanOP16mo ago
I just read that the second "as" makes it so that globalForPrisma has a property called prisma like globalForPrisma.prisma, but why was "as" designed to be used in this confusing way (both to assert a type and to instantiate a property of a certain type)?
barry
barry16mo ago
Stack Overflow
Typescript: Why does as unknown as x work
I have data its type is ItemDTO. I want to pass it into a function that accepts an argument of type Item. Typescript is complaining that this might be a mistake because the two types do not suffici...
Ryan
RyanOP16mo ago
This would make sense if i already had a typed variable that i needed to force fit to act as a different type, but if I'm just declaring and instantiating the variable right now, why cant i just do, const globalForPrisma = global as PrismaClient why do i have to get a child property involved or use unknown? this is the full file:
import { Prisma, PrismaClient } from "@prisma/client";

const globalForPrisma = global as unknown as {prisma:PrismaClient}

export const prisma =
globalForPrisma.prisma || new PrismaClient({log: ['query']})

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma
import { Prisma, PrismaClient } from "@prisma/client";

const globalForPrisma = global as unknown as {prisma:PrismaClient}

export const prisma =
globalForPrisma.prisma || new PrismaClient({log: ['query']})

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma
nvm figured it out its easier to just have a global object and see if that global object has a PrismaClient
Want results from more Discord servers?
Add your server