TypeScript:传入接口键名的函数无法正确推导返回类型
解决TypeScript键对应的类型精确推导问题
你的问题本质是函数参数key被推断为联合类型keyof MyInterface,导致返回值变成所有键对应类型的联合。要让TypeScript精确跟踪具体键的对应类型,需要用泛型约束捕获传入键的字面量类型。
修改后的核心代码
interface MyInterface { a: Something; b: SomethingElse; } const object: MyInterface = { a: {...}, b: {...}, } // 用泛型K约束key的类型,返回值严格对应MyInterface[K] const getValue = <K extends keyof MyInterface>(key: K): MyInterface[K] => { return object[key]; } const value = getValue('a'); // 类型为Something,符合预期
原理说明
泛型K会捕获你传入的具体键的字面量类型(比如调用时的'a'),而非整个keyof MyInterface联合类型。TypeScript会根据K的具体值,精确推导返回类型为MyInterface[K],从而避免返回联合类型。
Vuex组合式函数中的适配示例
假设你的Vuex状态结构如下,同样可以用泛型解决类型推导问题:
// 定义状态接口 interface AppState { userInfo: User; appSettings: Settings; } // 定义store const useAppStore = defineStore('app', { state: (): AppState => ({ userInfo: { id: 1, name: 'xxx' }, appSettings: { theme: 'dark', layout: 'side' } }) }); // 封装精确类型的状态获取函数 const getStoreValue = <K extends keyof AppState>(key: K): AppState[K] => { const store = useAppStore(); return store[key]; }; // 调用时类型自动推导正确 const currentUser = getStoreValue('userInfo'); // 类型为User const currentSettings = getStoreValue('appSettings'); // 类型为Settings
内容的提问来源于stack exchange,提问作者Arsen
相关产品推荐
相关产品推荐

