1

I found the difference in unknown and any when I was trying Deep Readonly

const f = () => 'string';

const a: { [key: string]: unknown } = f;
// Type '() => string' is not assignable to type '{ [key: string]: unknown; }'.
//  Index signature for type 'string' is missing in type '() => string'.

const b: { [key: string]: any } = f;
// no error

Why are functions assignable to { [key: string]: any }? I don't think functions have string keys.

Yz_4230
  • 11
  • 1
  • From [here](https://stackoverflow.com/a/38405226/102937): *"This tells the compiler that objects of type IEvent will have a string property called type, and elements of an IEvent object, accessed by the string index will be of any type."* – Robert Harvey Mar 19 '22 at 15:45
  • 1
    I'm not surprised to find a function is assignable to `{ [key: string]: any }`, I'd expect any object to be assignable to that, it's a very permissive type. It's interesting that `{ [key: string]: unknown }` does what you've shown above, though. And it happens with lots of objects, not just functions. `const f = new Date();`, `const f = new RegExp("x");`, `const f = new Number(42);`, they all do the same thing. But `const f = {answer: 42};` doesn't raise any error. For me, that's the surprising thing. – T.J. Crowder Mar 19 '22 at 15:55
  • 2
    Your question ends with a very direct question, but I don't think it's the question you're actually asking. I think you're really asking why those two index signatures treat functions *differently* from one another, right? – T.J. Crowder Mar 19 '22 at 15:56
  • @T.J.Crowder Thank you for your comments. I think the difference in `{answer: 42}` and `new Date()` is wheather it has a constructor, because of the type of newable objects will be `{ new(...args: any[]): any; }` and `new(...args: any[])` is not a `string`. – Yz_4230 Mar 19 '22 at 16:38

0 Answers0