【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.

相关推荐
宋拾壹10 分钟前
fastadmin列表中查看列表,并且添加增加相应的数据
javascript·php·fastadmin
墨痕诉清风26 分钟前
Linux系统设置上海时间(24小时制)
linux·运维·服务器
utf8mb4安全女神29 分钟前
脚本模块化
linux·运维·服务器
daad77733 分钟前
纪录无人机PID参数配置
linux
noipp40 分钟前
推荐题目:洛谷 P1737 [NOI2016] 旷野大计算
linux·数据结构·算法
枕星而眠1 小时前
Linux守护进程完全指南:从原理到实战
linux·运维·服务器·c++·后端
网络系统管理1 小时前
第八届江苏技能状元大赛选拔赛信息通信网络运行管理项目模块D网络服务与系统运维-Linux样题解析
linux·运维·网络
云水一下1 小时前
Vue.js从零到精通系列(三):组件化基础——Props、Emits、插槽与生命周期
前端·javascript·vue.js
不会C语言的男孩1 小时前
Linux 系统编程 · 第 2 章:系统调用与库函数
linux·c语言
坤昱1 小时前
cfs调度类深入解刨——psi科普篇
linux·cfs·psi·cfs调度·eevdf·psi详细分析·linux系统资源监控