typescript 如何通过传递接口属性作为参数来推断接口属性的类型?

xqnpmsa8  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(170)

下面是我例子:

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');

我想通过传递接口键来获取正确的类型,因为上面的示例字段应该是布尔型

68bkxrlz

68bkxrlz1#

你可以用curried函数来实现这一点:

const injectRecord = <T>(): T => ({ n: 123, s: 'abc', b: true } as T);

const getField = <T extends Record<string, unknown>>() => <K extends keyof T>(key: K): { field: T[K] } => {
    const record = injectRecord<T>();
    return { field: record[key] };
}

const { field } = getField<{ n: number; s: string; b: boolean }>()('b');
//       ^? const field: boolean

请参阅TypeScript Playground。由此评论提示

相关问题