TypeScript嵌套对象类型报错:为何仅第一个对象提示属性不存在?
问题:TypeScript类型定义报错,仅第一个对象触发错误的原因?
我尝试为包含嵌套对象的变量定义类型时遇到错误,错误提示为:
Object literal may only specify known properties, and '"0x63564c40"' does not exist in type 'Network'.
相关代码如下:
export interface Network { network: { chainId: string; rpcUrls: string[]; chainName: string; nativeCurrency: { name: string; symbol: string; decimals: number; }; blockExplorerUrls: string[]; iconUrls: string[]; }; } export const networkParams: Network = { "0x63564c40": { chainId: "0x63564c40", rpcUrls: ["https://api.harmony.one"], chainName: "Harmony Mainnet", nativeCurrency: { name: "ONE", decimals: 18, symbol: "ONE" }, blockExplorerUrls: ["https://explorer.harmony.one"], iconUrls: ["https://harmonynews.one/wp-content/uploads/2019/11/slfdjs.png"], }, "0xa4ec": { chainId: "0xa4ec", rpcUrls: ["https://forno.celo.org"], chainName: "Celo Mainnet", nativeCurrency: { name: "CELO", decimals: 18, symbol: "CELO" }, blockExplorerUrl: ["https://explorer.celo.org"], iconUrls: ["https://celo.org/images/marketplace-icons/icon-celo-CELO-color-f.svg"], }, };
请问为何仅第一个对象触发该错误,第二个对象却没有?
解答
核心原因:接口定义与实际变量结构不匹配
你定义的Network接口要求对象必须包含network字段,但实际的networkParams是一个以链ID字符串为键、链配置对象为值的字典结构,完全不符合接口约定。TypeScript检测到你传入的对象里没有network属性,反而存在0x63564c40这种接口未定义的属性,因此抛出错误。
为什么第二个对象没触发相同错误?
第二个对象里存在拼写错误:把blockExplorerUrls写成了blockExplorerUrl(少了末尾的s)。TypeScript的错误检测逻辑会优先处理内层对象的属性不匹配问题,同时由于外层已经存在类型不匹配的错误,后续键的错误被暂时抑制了。如果你修正第二个对象的拼写错误,会发现0xa4ec也会触发同样的未知属性错误。
修复方案
修正Network接口的定义,让它匹配实际的字典结构:
// 定义单个链的配置类型 export interface ChainConfig { chainId: string; rpcUrls: string[]; chainName: string; nativeCurrency: { name: string; symbol: string; decimals: number; }; blockExplorerUrls: string[]; iconUrls: string[]; } // 定义以链ID为键的字典类型(两种写法二选一) export type Network = Record<string, ChainConfig>; // 或者:export interface Network { [chainId: string]: ChainConfig; } export const networkParams: Network = { "0x63564c40": { chainId: "0x63564c40", rpcUrls: ["https://api.harmony.one"], chainName: "Harmony Mainnet", nativeCurrency: { name: "ONE", decimals: 18, symbol: "ONE" }, blockExplorerUrls: ["https://explorer.harmony.one"], iconUrls: ["https://harmonynews.one/wp-content/uploads/2019/11/slfdjs.png"], }, "0xa4ec": { chainId: "0xa4ec", rpcUrls: ["https://forno.celo.org"], chainName: "Celo Mainnet", nativeCurrency: { name: "CELO", decimals: 18, symbol: "CELO" }, blockExplorerUrls: ["https://explorer.celo.org"], // 修正拼写错误 iconUrls: ["https://celo.org/images/marketplace-icons/icon-celo-CELO-color-f.svg"], }, };
内容的提问来源于stack exchange,提问作者Furkan Öztürk
相关产品推荐
相关产品推荐

