1

This is a dumb question but I have a function that does:

export function parseSomething(someList: string[]): string[] {
    someList.forEach((someField: string) => {
        console.log(typeof someField)
    })

someField is being read as an object. Why? The object being passed to this function is a string array.

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
Avi Jain
  • 99
  • 1
  • 8
  • You must be passing it an an array of objects. something like `parseSomething([{},{}] as any)`. Log it, scan your codebase for invocations, make sure they seem typed correctly etc – Yuji 'Tomita' Tomita Aug 18 '22 at 00:17
  • I pasted an answer. Take a look at it please. – Youssouf Oumar Aug 18 '22 at 02:50
  • Does this answer your question? [How do I check if a variable is an array in JavaScript?](https://stackoverflow.com/questions/767486/how-do-i-check-if-a-variable-is-an-array-in-javascript) – about14sheep Aug 18 '22 at 19:30

1 Answers1

1

The typeof operator returns a string indicating the type of the unevaluated operand. It does work on execution time, so there is no TypeScript at this point. And there is no array type in JavaScript, as arrays are objects. You can read on mdn for more about JavaScript types.

Arrays exist only while writing code with your linter and on compilation time with your compilator as it's a TypeScript only type. You can use Array.isArray() to test if someField is an array on execution time, like so as an example:

console.log(Array.isArray(someField))

It's to know that there is a typeof specific to TypeScript that's different from the above one, that can be used in type definition, like so:

let s = "hello";
let n: typeof s;
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
  • Hmm I don't think this answers the question. Additionally, I expect a strongly typed language to either throw an exception when an incorrect type is passed but for some reason that doesn't happen here – Avi Jain Aug 18 '22 at 05:06
  • Yeah but that's how JavaScript is, and why we need TypeScript. And even combined, they are not a dynamically typed language. – Youssouf Oumar Aug 18 '22 at 05:15
  • 1
    @AviJain this 100% answers the question. You can [see here](https://jsfiddle.net/jr4932mx/) that calling typeof on an array will return `object`. Also, JavaScript is not a strongly typed language (which a big reason why typescript is a thing). As @yousoumar also stated, typescript does not exist at runtime and therefore doesn't throw any exceptions. You can find more information about what typescript is [here](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html) – about14sheep Aug 18 '22 at 19:28