TypeScript接口无法赋值给JsonValue类型但同结构类型别名可正常使用的问题求助
TypeScript接口无法赋值给JsonValue类型但同结构类型别名可正常使用的问题求助
大家好,我最近在做TypeScript的JSON序列化相关开发时,碰到了一个挺有意思的类型兼容性问题,想请教下各位~
问题详情
我定义了一个JsonValue联合类型,用来表示可以安全序列化为JSON的值,同时写了一个接受该类型参数的函数。奇怪的是,当我尝试把一个接口实例传给这个函数时会触发类型错误,但换成结构完全一致的类型别名,却能正常运行:
// 定义JSON可序列化的联合类型 type JsonValue = | string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; // 接口定义 interface User { name: string; age: number; } // 同结构的类型别名 type UserType = { name: string; age: number; }; // 接受JsonValue类型的序列化函数 function serializeJson(value: JsonValue): string { return JSON.stringify(value); } // ❌ 这里会报错:类型“User”的参数不能赋给类型“JsonValue”的参数 const user: User = { name: "Alice", age: 30 }; serializeJson(user); // ✅ 完全相同结构的类型别名却可以正常传递 const userType: UserType = { name: "Bob", age: 25 }; serializeJson(userType);
实在搞不懂为什么结构一模一样,接口和类型别名在这个场景下会有不同的表现,有没有大佬能帮忙拆解下这背后的TypeScript类型检查逻辑呀?
备注:内容来源于stack exchange,提问作者wch
相关产品推荐
相关产品推荐

