Typescript 从参数部分推断泛型索引类型

Typescript 从参数部分推断泛型索引类型,typescript,Typescript,我已创建此帮助器函数: 导出函数createStyleUtilForProp( 道具:K, 样式:((val:TProps[K])=>RNStyle)| RNStyle, ) { 返回(道具:TProps)=>{ if(typeof style==='function'){ 返回样式(道具[道具]); } 返回道具【道具】?样式:空; } } 我想使用它如下: type Props = { border?: number; color?: string, } const getBor

我已创建此帮助器函数:

导出函数createStyleUtilForProp(
道具:K,
样式:((val:TProps[K])=>RNStyle)| RNStyle,
) {
返回(道具:TProps)=>{
if(typeof style==='function'){
返回样式(道具[道具]);
}
返回道具【道具】?样式:空;
}
}
我想使用它如下:

type Props = {
  border?: number;
  color?: string,
}

const getBorderStyle = createStyleUtilForProp<Props>('border', (border) => ({
  borderWidth: border,
  borderColor: '#000000',
}));

我不喜欢把
'border'
放两次。TS是否有任何方法可以从参数推断索引类型?

typescript up至少3.3(撰写本文时的下一个版本)中不支持部分推断

有一个建议允许在3.4中进行部分推断(如详细所述),但至少从3.1开始,它已经倒退了,因此它何时进入是不确定的。有了这个建议,你可能能够写(我说可能,因为我是根据问题中描述的行为进行推测的)

const getBorderStyle = createStyleUtilForProp<Props, 'border'>('border', ...);
const getBorderStyle = createStyleUtilForProp<Props, _>('border', (border) => ({
    borderWidth: border,
    borderColor: '#000000',
}));
export function createStyleUtilForProp<TProps>() {

    return function <K extends keyof TProps>(
        prop: K,
        style: ((val: TProps[K]) => RNStyle) | RNStyle,
    ) {
        return (props: TProps) => {
            if (typeof style === 'function') {
                return style(props[prop]);
            }
            return props[prop] ? style : null;
        }
    }
}
type Props = {
    border?: number;
    color?: string,
}

const getBorderStyle = createStyleUtilForProp<Props>()('border', (border) => ({
    borderWidth: border,
    borderColor: '#000000',
}));