如何在TypeScript的Branch接口中使用State枚举?
用State枚举改造Branch接口的方案
嘿,作为TypeScript新手碰到这种类型定义的问题很正常,我来帮你捋清楚怎么实现用State.NEWYORK、State.BOSTON来访问Branch的对应属性!
核心思路是把枚举作为接口/类型的键类型,TypeScript支持用枚举成员来定义对象的键,具体有两种常用方式:
方式一:使用映射类型定义接口
你可以通过[key in State]这种映射语法,让Branch接口的键完全对应State枚举的成员:
interface Products { asian: {[key: string]: string}; american: {[key: string]: string}; } enum State { NEWYORK = 'nyc', BOSTON = 'boston' } // 映射State枚举的每个成员作为Branch的键 interface Branch { [key in State]: { products: Products }; }
这样定义后,Branch的键只能是State.NEWYORK(对应字符串'nyc')和State.BOSTON(对应字符串'boston'),使用时可以直接通过枚举值访问:
// 正确的示例 const cityBranches: Branch = { [State.NEWYORK]: { products: { asian: { sushi: 'fresh' }, american: { burger: 'juicy' } } }, [State.BOSTON]: { products: { asian: { ramen: 'creamy' }, american: { clams: 'steamed' } } } }; // 通过枚举值访问属性,完全符合你的需求 console.log(cityBranches[State.NEWYORK].products.asian.sushi); // 输出 'fresh'
方式二:使用内置Record工具类型(更简洁)
TypeScript提供了内置的Record<K, T>工具类型,专门用于定义“键类型为K,值类型为T”的对象结构,用它来实现会更简洁:
interface Products { asian: {[key: string]: string}; american: {[key: string]: string}; } enum State { NEWYORK = 'nyc', BOSTON = 'boston' } // 用Record直接生成Branch类型,效果和方式一完全一致 type Branch = Record<State, { products: Products }>;
额外优势
无论用哪种方式,当你以后给State枚举新增成员时(比如CHICAGO = 'chicago'),TypeScript会自动提示你在Branch对象中添加对应的属性,避免了硬编码键名可能带来的遗漏,代码的可维护性会大大提升!
内容的提问来源于stack exchange,提问作者Aniks
相关产品推荐
相关产品推荐

