下面是我例子:
export const getField = <T extends Record<string, any>, K extends keyof T = keyof T>(fieldName: K) => {
const record = injectRecord<T>(); // sideEffect
return { field: record[fieldName] };
};
// in real life here will be different objects
const injectRecord = <T>() => ({ number: 123, bool: true, string: 'asd' } as T);
// typeof field = string | number | boolean
const { field } = getField<{ number: number; string: string; bool: boolean }>('bool');
我想通过传递接口键来获取正确的类型,因为上面的示例字段应该是布尔型
1条答案
按热度按时间68bkxrlz1#
你可以用curried函数来实现这一点:
请参阅TypeScript Playground。由此评论提示