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

相关推荐
山河木马5 小时前
渲染管线-计算得到gl_Position(顶点着色器)之后续GPU流程
javascript·webgl·图形学
竹林8185 小时前
用 The Graph 查询链上数据实战:从手搓 RPC 到 Subgraph,我的 NFT 项目数据加载快了 10 倍
前端·javascript
kyriewen8 小时前
别再每次都 Google 了:我整理了前端日常最常踩的 10 个 Git 坑,附速查表
前端·javascript·git
SmartBoyW9 小时前
深入ECMAScript规范:彻底搞懂JS隐式类型转换与底层ToPrimitive机制
前端·javascript
用户852495071849 小时前
解密 JavaScript 中的 this:谁才是真正的调用者?
javascript·面试
Heo10 小时前
Vite进阶用法详解
前端·javascript·面试
铁皮饭盒11 小时前
Next.js 风格路由内置?Bun FileSystemRouter 凭啥这么香
javascript
小林ixn12 小时前
别再背八股了!从 5 个真实场景彻底搞懂 JavaScript 的 this
javascript
东风破_12 小时前
JavaScript 面试常考的字符串算法:从反转字符串到回文判断
前端·javascript
巴勒个啦12 小时前
D3.js 入门实战:用力导向图可视化项目依赖关系
javascript