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

相关推荐
六月June June1 天前
自定义调色盘组件
前端·javascript·调色盘
万象.1 天前
Linux传输层TCP,UDP相关内容
linux·tcp/ip·udp
SY_FC1 天前
实现一个父组件引入了子组件,跳转到其他页面,其他页面返回回来重新加载子组件函数
java·前端·javascript
糟糕好吃1 天前
我让 AI 操作网页之后,开始不想点按钮了
前端·javascript·后端
陈天伟教授1 天前
人工智能应用- 天文学家的助手:08. 星系定位与分类
前端·javascript·数据库·人工智能·机器学习
MaximusCoder1 天前
等保测评命令——Centos Linux
linux·运维·经验分享·python·安全·centos
万象.1 天前
Linux数据链路层通信原理及报文格式
linux·网络·网络协议
卷Java1 天前
Linux服务器Docker部署OpenClaw:腾讯云/阿里云/VPS安装避坑指南
linux·运维·服务器
颜酱1 天前
BFS 与并查集实战总结:从基础框架到刷题落地
javascript·后端·算法
小彭努力中1 天前
191.Vue3 + OpenLayers 实战:可控化版权信息(Attribution)详解与完整示例
前端·javascript·vue.js·#地图开发·#cesium