如何基于Structure类型约束TypeScript对象与函数的输入参数
TypeScript类型约束:根据结构类型动态限制子类型输入
基础类型定义
export const structureTypes = ["atom", "molecule"] as const export type Structure = typeof structureTypes[number] export const atomTypes = [ "hydrogen", "oxygen", "argon", ] as const export const moleculeTypes = [ "water", "methane", ] as const export type AtomType = typeof atomTypes[number] export type MoleculeType = typeof moleculeTypes[number]
问题说明
你当前的StructureIdCache允许一级键为"atom"时使用"water"这类无效二级键,同时getTypeId函数无法根据传入的type参数动态约束name的合法取值。以下是针对性解决方案:
1. 修正StructureIdCache类型
先建立结构类型到子类型的映射关系,再通过映射类型生成严格约束的缓存结构:
// 定义结构与子类型的关联映射 type StructureToType = { atom: AtomType; molecule: MoleculeType; }; // 重构后的缓存类型 export type StructureIdCache = { [K in keyof StructureToType]: { [SubK in StructureToType[K]]: string; }; };
此时StructureIdCache的"atom"字段仅允许AtomType的键,"molecule"字段仅允许MoleculeType的键,彻底避免无效键问题。
2. 修正getTypeId函数的类型约束
通过泛型约束实现参数间的关联,让name的类型随type的取值动态变化:
// 复用结构与子类型的关联映射 type StructureToType = { atom: AtomType; molecule: MoleculeType; }; export const getTypeId = async <T extends Structure>( c: Context, type: T, name: StructureToType[T] ): Promise<string> => { // 业务逻辑实现 };
调用函数时TypeScript会自动做关联校验:
- 当
type传入"atom",name只能选择"hydrogen"/"oxygen"/"argon" - 当
type传入"molecule",name只能选择"water"/"methane"
内容的提问来源于stack exchange,提问作者Harry
相关产品推荐
相关产品推荐

