【Typescript】未知类型如何处理?

The error happens because Prisma's Json type is a union of all valid JSON types: string | number | boolean | null | JsonObject | JsonArray.

TypeScript is complaining because a string or a number does not have a property named low_number . Even though you know user.data is likely an object, TypeScript must account for the possibility that it might be a primitive value.

Here are the three best ways to fix this:

1. The Cleanest Way (Type Assertion)

If you are confident that data is an object (or null), you can cast it to a custom interface or any. This is the most common approach for Prisma JSON fields.

typescript 复制代码
// Define what your JSON looks like
interface UserData {
  low_number?: number;
}

const low_number = (user.data as UserData)?.low_number ?? -1;

2. Using Prisma's JsonObject type

If you don't want to create a custom interface, you can cast it to Prisma's built-in JsonObject type. You must import it from @prisma/client.

typescript 复制代码
import { Prisma } from '@prisma/client';

// ...

const data = user.data as Prisma.JsonObject;
const low_number = data?.low_number ?? -1;

3. The "Quick and Dirty" Way

If you don't care about strict typing for this specific variable, cast it to any.

typescript 复制代码
const low_number = (user.data as any)?.low_number ?? -1;

4. The Safest Way (Type Guard)

If you want to be 100% safe at runtime to ensure the code doesn't crash if the JSON is malformed (e.g., it's actually a string), check the type:

typescript 复制代码
let low_number = -1;

if (user.data && typeof user.data === 'object' && !Array.isArray(user.data)) {
  const data = user.data as Record<string, any>;
  low_number = data.low_number ?? -1;
}

Why your original code failed:

typescript 复制代码
// This fails because even if user.data is truthy, 
// it might be the string "hello", and "hello".low_number is invalid.
user.data && user.data.low_number 

Recommendation: Use Option 1 . Defining an interface makes your code much more maintainable as your data field grows with more properties.

相关推荐
梵得儿SHI2 小时前
Vue Router 路由管理从入门到精通:基础、导航与参数传递实战(含避坑指南)
前端·javascript·vue.js·路由基础配置·版本适配·路由实例创建·路由规则定义
Watermelo6172 小时前
【前端实战】Axios 错误处理的设计与进阶封装,实现网络层面的数据与状态解耦
前端·javascript·网络·vue.js·网络协议·性能优化·用户体验
不一样的少年_2 小时前
【性能监控】别只做工具人了!手把手带你写一个前端性能检测SDK
前端·javascript·监控
开发者小天2 小时前
react中使用复制的功能
前端·javascript·react.js
wanderful_2 小时前
Javascript笔记分享-流程控制(超级超级详细!!!)
javascript·笔记·流程控制·实战案例·新手友好
杨江2 小时前
Jenkins on Linux安装部署
linux·运维·jenkins
知识分享小能手2 小时前
Ubuntu入门学习教程,从入门到精通,Ubuntu 22.04 的 Vim 编辑器 —— 全面详解(含基础操作、高级技巧与编程实践)(5)
linux·学习·ubuntu
_OP_CHEN2 小时前
【Linux系统编程】(十六)揭秘 Linux 程序地址空间:从虚拟地址到内存管理的底层逻辑实战
linux·操作系统·虚拟地址空间·系统编程·进程地址空间·虚拟内存管理·程序地址空间
有谁看见我的剑了?2 小时前
Linux ssh连接超时时间学习
linux·学习·ssh