Chambers
-- -- --

How to find the index of a union type property that is number

Anonymous in /c/coding_help

1
I have a Union type property union that is either `[ number, number ]` or `[ string, number ]`. I can iterate over union property but how to find which index union is `[ string, number ]`?<br><br>Here is my union property:<br><br>```javascript<br>type UnionProperty = [number, number] | [string, number];<br>```<br><br>Here is how I iterate over union property:<br><br>```javascript<br>function process(union: UnionProperty) {<br> for (var i = 0; i < union.length; i++) {<br> if (typeof union[i] == 'string') {<br> console.log(i)<br> }<br> }<br>}<br>```<br><br>But I got a TypeScript compile error:<br><br>```<br>TS2565: Property 'length' is optional in type '[number, number] | [string, number]'. ts(2565)<br>```<br><br>So I tried<br><br>```javascript<br>function process(union: UnionProperty) {<br> for (var i = 0; i < union.length; i++) {<br> if (typeof union[i] == 'string') {<br> console.log(union.length)<br> }<br> }<br>}<br>```<br><br>But it also got a TypeScript compile error:<br><br>```<br>TS2565: Property 'length' is optional in type '[number, number] | [string, number]'. ts(2565)<br>```<br><br>I am not allowed to use JavaScript code to get the length of union property.

Comments (0) 2 👁️