How do I add an index signature for a mapped type?

后端 未结 1 2029
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-07 12:33

Suppose I have interface

interface X {
   a: string;
   b: number;
   c: boolean;
}

and a function

function values(x: X) {
            


        
相关标签:
1条回答
  • 2021-02-07 13:21

    You can:

    interface X {
        a: string;
        b: number;
        c: boolean;
        [key: string]: X[keyof X];
    }
    

    The result of X[keyof X] will now be (string | number | boolean), which works even better than any because the return of your function will be (string | number | boolean)[].

    Example

    Another way that should work with both examples is:

    function values(x: X) {
        const keys = Object.keys(x) as (keyof X)[];
        return keys.map(s => x[s]);
    }
    

    Not pretty, but at least more typed than (x as any).

    Of course it can be made generic too:

    function values<T>(x: T) {
        const keys = Object.keys(x) as (keyof T)[];
        return keys.map(s => x[s]);
    }
    
    0 讨论(0)
提交回复
热议问题