0

Why does a void function pass as a plain object? Is there a good reason for this, or is it a bug?

playground

type PlainObject = { [key: string]: any };

const foo = (value: PlainObject) => { }

const voidFn: () => void = () => { };

// Error as expected
foo(false);
foo(3);
foo('test');

foo ({ test: true }) // ok - expected usage

foo(voidFn); // Why does it not trigger an error?

The problem occurs only if the value is any. If it was { [key: string]: string }; for instance, the error would occur.

1
  • Almost everything in JavaScript is an object. In fact, only six things are not objects. They are — null , undefined , strings, numbers, boolean, and symbols. These are called primitive values or primitive types Commented Apr 10, 2021 at 16:03

1 Answer 1

2

Functions are objects.

const f = () => null;
const o = {};

console.log(f instanceof Object);
console.log(o instanceof Object);

Since every property of the PlainObject can have any value, it doesn't matter what properties the function has.

Sign up to request clarification or add additional context in comments.

1 Comment

Makes sense. For some reason, I thought TypeScript would abstract that away in the types, but I see how even a (() => { }).name is a valid operation, so it has to be that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.