1

Apparently when assigning a value to a function type, the argument types should be an exact match. For example assigning a function with type:

(arg: {prop: string}) => void

to a variable with type:

(arg: object) => void

will throw error that:

Type '(arg: {prop: string;}) => void' is not assignable to type '(arg: object) => void'. Types of parameters 'arg' and 'arg' are incompatible. Property 'prop' is missing in type '{}' but required in type '{ prop: string; }'

typescript playground

Any help or explanation about the purpose of this behavior is appreciated, why typescript does not accept any object type for arguments with type object in this scenario?

20
  • Because type object doesn't guarantee there is key prop. This Commented Sep 12, 2023 at 11:28
  • but isnt' that the purpose of type object? to accept any object. because for example here const v:object = { prop: '' };, any object is accepted for variable v Commented Sep 12, 2023 at 11:32
  • I think object is like any because almost everything is js is object exception for some primitives See this. And Typescript need to make sure that your function will accept the prop key since object is any object if you doesn't pass the prop key it will throw error in runtime and typescript is trying to prevent that. Commented Sep 12, 2023 at 11:34
  • so there is no way in typescript to define a function type to accept all functions with object argument type? Commented Sep 12, 2023 at 11:36
  • 1
    Functions are contravariant in their parameter types, at least with --strictFunctionTypes enabled (see docs). This is for safety reasons. Yes, every {prop: string} is an object, but not every function that accepts any {prop: string} argument is one that accepts any object argument. See other linked q/a for more info Commented Sep 12, 2023 at 15:18

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.