如何为TypeScript对象属性编写类型安全的更新函数?
解决TypeScript类型关联问题
你需要用索引访问类型来获取MyItem的value属性类型,把MyDictionary[Type].value改成MyDictionary[Type]['value']即可,这是TypeScript中访问嵌套属性类型的正确写法。
正确的类型定义与实现
interface MyItem<Type> { value: Type; description: string; } interface MyDictionary { someNumber: MyItem<number>; someString: MyItem<string>; truthOrFalsehood: MyItem<boolean>; } const myDictionary: MyDictionary = { someNumber: { value: 1, description: "Math", }, someString: { value: "abc", description: "Language", }, truthOrFalsehood: { value: true, description: "Philosophy", }, }; // 修正后的UpdateFunction类型 type UpdateFunction = <Type extends keyof MyDictionary>( key: Type, value: MyDictionary[Type]['value'], // 正确的嵌套属性类型访问 ) => void; const update: UpdateFunction = (key, value) => { myDictionary[key].value = value; }; update("someNumber", 7); // 合法,类型匹配 update("foo", "bar"); // 编译错误,"foo"不是MyDictionary的合法key update("someString", 123); // 编译错误,value类型应为string而非number
补充说明
如果想让类型定义更清晰,也可以通过条件类型+infer来提取MyItem的泛型参数:
type ItemValue<T> = T extends MyItem<infer V> ? V : never; type UpdateFunction = <Type extends keyof MyDictionary>( key: Type, value: ItemValue<MyDictionary[Type]>, ) => void;
这种写法更直观地表达了“提取MyItem包裹的类型”的意图,效果和直接索引访问一致。
内容的提问来源于stack exchange,提问作者Robo Robok
相关产品推荐
相关产品推荐

