-1

Why does func1 work as expected while func2 shows error?

type AnyObj = Record<string, any>;
type Data = { a: number; b: string };
type DataFunction = (arg: AnyObj) => any;

const func1: DataFunction = () => {};
const arg1: Data = {} as any; 
func1(arg1); // great

const func2 = (arg: { func: DataFunction }) => {};
const arg2: { func: (arg: Data) => { } } = {} as any; 
func2(arg2); // why not ok?

TS Playground

user5480949
  • 1,410
  • 1
  • 15
  • 22
  • 1
    Looks like you are another victim of function contravariance. I explained in an [earlier answer](https://stackoverflow.com/questions/75915082/why-does-using-unknown-type-to-represent-types-that-i-dont-mind-instead-of-a/75915162#75915162), but you can also see [this answer](https://stackoverflow.com/questions/66410115/difference-between-variance-covariance-contravariance-and-bivariance-in-typesc) and [this article](https://dmitripavlutin.com/typescript-covariance-contravariance/) – kelsny Apr 05 '23 at 18:51

1 Answers1

0

I had to add a type parameter to func2:

type DataFunction<A extends AnyObj = AnyObj> = (arg: A) => any;

const func2 = <D extends AnyObj, >(arg: { func: DataFunction<D> }) => {};
const arg2: { func: (arg: Data) => { } } = {} as any; 
func2(arg2); // ok
user5480949
  • 1,410
  • 1
  • 15
  • 22