Hacker News new | ask | show | jobs
by headbee 1131 days ago
I believe that would be covariant: `'home' | 'work'` is a subtype of `string`, and `Record<'home' | 'work', number>` is assignable to `Record<string, number>` so the subtype relationship is preserved.
1 comments

I don't follow how this parameter works then in Record:

  const taskCounts = { work: 10, home: 5, personal: 3 };

  const what : Record<string, number> = taskCounts; // OK, covariance?
  const the : Record<"work" | "home", number> = taskCounts; // Also OK, contravariance?
  const hell : Record<"work" | "home" | "personal" | "hello", number> = taskCounts; // This is an error
https://www.typescriptlang.org/play?#code/MYewdgzgLgBFCGEDWB...
I think you were originally correct and that `Record<string, number>` was not a good example. I would guess that union literals and primitives are handled differently by the compiler in this case, perhaps because a record with keys of every possible string is impossible it may have a special condition to skip some typing rules. In fact, `Record<number, number>` is assignable to `Record<string, number>`.