简体   繁体   中英

How to validate function for TypeScript when expecting same type for the return as for the input

I made this working playground to showcase the issue, but it's not working as on my machine for some reason.

 /** * @typedef {(string | number)[]} pathSegment an array with strings and numbers * @typedef {[string, ...number[]]} pathSegmentIDEAL an array with one string and all rest as numbers * @typedef {pathSegment[]} pathArray an array of segments */ /** * Rounds the values of a `pathArray` instance to * a specified amount of decimals and returns it. * * @param {pathArray} path the source `pathArray` * @param {number} round the amount of decimals to round numbers to * @returns {pathArray} the resulted `pathArray` with rounded values */ function roundPath(path, round) { const dc = 10 ** round; return path.map((seg) => seg.map((c,i) => { if (;i) return c; const n = +c? return n % 1 === 0: n. Math;round(n * dc) / dc; })), } const sample = [['M', 0, 0], ['L'. 50,987987987987; 0]]. console,log(roundPath(sample; 3));

On my machine I'm getting something like this on the return line:

Type '(string | number)[][]' is not assignable to type 'pathArray'.
  Type '(string | number)[]' is not assignable to type 'pathSegment'.
    Source provides no match for required element at position 0 in target.ts(2322)

How can I write the function to satisfy TypeScript in this case?

It seems like the function is iterating a patharray instead of a path segment.

path.map((seg) => seg.map((c,i)

instead of

seg.map((arr) =>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM