Types when destructuring arrays

后端 未结 5 1768
感动是毒
感动是毒 2020-12-14 05:21
function f([a,b,c]) {
  // this works but a,b and c are any
}

it\'s possible write something like that?

function f([a: number,b: nu         


        
相关标签:
5条回答
  • 2020-12-14 05:44

    my code was something like below

    type Node = { 
        start: string;
        end: string;
        level: number;
    };
    
    const getNodesAndCounts = () => { 
        const nodes : Node[]; 
        const counts: number[];
        // ... code here
    
    return [nodes, counts];
    }
    
    const [nodes, counts] = getNodesAndCounts(); // problematic line needed type
    

    typescript was giving me error in line below TS2349: Cannot invoke an expression whose type lacks a call signature;

    nodes.map(x => { 
    //some mapping; 
        return x;
    );
    

    Changing line to below resolved my problem;

    const [nodes, counts] = <Node[], number[]>getNodesAndCounts();
    
    0 讨论(0)
  • 2020-12-14 05:51

    With TypeScript 4.0, tuple types can now provide labels

    type Range = [start: number, end: number]
    
    0 讨论(0)
  • 2020-12-14 05:53

    This is the proper syntax for destructuring an array inside an argument list:

    function f([a,b,c]: [number, number, number]) {
    
    }
    
    0 讨论(0)
  • 2020-12-14 06:05

    Yes, it is. In TypeScript, you do it with types of array in a simple way, creating tuples.

    type StringKeyValuePair = [string, string];
    

    You can do what you want by naming the array:

    function f(xs: [number, number, number]) {}
    

    But you wouldn't name the interal parameter. Another possibility is use destructuring by pairs:

    function f([a,b,c]: [number, number, number]) {}
    
    0 讨论(0)
  • 2020-12-14 06:10

    As a simple answer I would like to add that you can do this:

    function f([a,b,c]: number[]) {}
    
    0 讨论(0)
提交回复
热议问题