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

相关推荐
水饺编程几秒前
第2章:Linux 基础,clear 命令
linux·c语言·汇编
古夕11 分钟前
iframe 授权失败时露出 60000 JSON 的复盘
前端·javascript
程序员Sunday26 分钟前
ES Module 和 CommonJS 有什么区别?循环依赖时会发生什么?
前端·javascript·面试
三十而立洋38 分钟前
TypeScript 7.0 深度解析:新特性、Go 原生编译器及与 TypeScript 6.0 的区别
前端·typescript·前端工程化
VimorphTech43 分钟前
React 自动保存怎么设计?防抖、串行请求与导出前等待
后端·typescript
GeW1 小时前
新质生产力路线图Linux和数据库自主可控实践指南
linux
yunwei371 小时前
eBPF 教程:BPF 迭代器用于内核数据导出
linux·后端·性能优化
有味道的男人1 小时前
搜好货平台关键词商品搜索接口:分页容错与商品数据轻量化提取方案
服务器·前端·javascript
别动我齐刘海2 小时前
实时控制学习2
linux·c++·人工智能·学习·算法
行者-全栈开发2 小时前
【容器/虚拟化】CVE-2026-53359:Linux KVM Januscape 虚拟机逃逸漏洞修复指南(潜伏16年的云安全噩梦)
linux·运维·服务器·多租户隔离·cve-2026-53359·kvm虚拟机逃逸·shadow mmu