函数的返回类型是否可以依赖于输入参数的值?

问题描述 投票:0回答:1

给定一个接口,我想创建一个选择该接口属性的函数,该属性可以指定为输入参数。

这是我最接近的:

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输入参数。这可能吗?

Here's a link to the example in the TypeScript playground.

typescript
1个回答
1
投票

你非常接近,但是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];
}

Playground link

© www.soinside.com 2019 - 2024. All rights reserved.