1

I am writing a small helper function in TypeScript.

This doesn't compile:

export function newArray<T>(size: number, init: T | ((index: number) => T)): T[] {
    if (typeof init === 'function') {
        return Array(size).fill(0).map((_, i) => init(i))
    } else {
        return Array(size).fill(init)
    }
}

While this does:

export function newArray<T>(size: number, init: T | ((index: number) => T)): T[] {
    if (init instanceof Function) {
        return Array(size).fill(0).map((_, i) => init(i))
    } else {
        return Array(size).fill(init)
    }
}

Why the difference?

Nikola Mihajlović
  • 2,286
  • 2
  • 19
  • 23
  • Does this answer your question? [Why does instanceof return false for some literals?](https://stackoverflow.com/questions/203739/why-does-instanceof-return-false-for-some-literals) – Alexandra Petrova Apr 16 '20 at 14:35

0 Answers0