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

相关推荐
INS_KF12 分钟前
【编程笔记】成员函数中两个 const 的区别(const Data &getData() const;)
前端·javascript·笔记
宿67444 分钟前
vue3-async
前端·javascript·vue.js
excel2 小时前
Nuxt + Twin CSS 中宽度超过屏幕时底部出现空白的原因与解决方案
前端·javascript
开心大爆炸4 小时前
xrdp 连接 登录对话框输入密码后闪退
linux·运维·服务器
oushaojun24 小时前
大厂 C++ 面试:深度剖析 Linux Signal 信号机制(转)
linux
一个游离的指针5 小时前
函数管道:消除深度嵌套调用
前端·javascript
PBitW5 小时前
为什么vite中TS报错,可以继续运行?Webpack不行?
前端·webpack·typescript·vite
苏生Susheng5 小时前
【软件实施】Linux系统Shell脚本教程
linux·运维·服务器·chrome·spring boot·学习·实施
Ruiery5 小时前
Linux 6.6内核 IOMMU 深度解析(七):DMA API 与 IOMMU 集成 — 从 dma_map_single 到 iommu_map
linux·运维·服务器
柚yuzumi5 小时前
前端优化,从少触发一次开始:防抖与节流
前端·javascript