给定一个接口,我想创建一个选择该接口属性的函数,该属性可以指定为输入参数。
这是我最接近的:
interface Source {
a?: string;
b?: boolean;
c?: number;
}
function getPropertyFromFirstExisting(
arr: Source[],
property: keyof Source
): Source[keyof Source] {
return arr.map(el => el[property]).filter(prop => !!prop)[0];
}
const sourceArr = [
{ a: 'asdf', c: 12 },
{ b: true }
];
interface Target {
a: string;
b: boolean;
c: number;
}
const result: Target = {
// the property result.a should only be string type
a: getPropertyFromFirstExisting(sourceArr, 'a'),
// the property result.b should only be boolean type
b: getPropertyFromFirstExisting(sourceArr, 'b'),
// the property result.c should only be number type
c: getPropertyFromFirstExisting(sourceArr, 'c')
};
在这种情况下,getPropertyFromFirstExisting
有一个返回类型string | boolean | number
,但有一个很好的解决方案,它应该只是其中之一,这取决于property
输入参数。这可能吗?
你非常接近,但是Source[keyof Source]
会给你一个Source
中所有可能值的联合你需要一个额外的类型参数来捕获传入的实际键并使用它来输入查询到Source
:
function getPropertyFromFirstExisting<K extends keyof Source>(
arr: Source[],
property: K
): Source[K] {
return arr.map(el => el[property]).filter(prop => !!prop)[0];
}