TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Records should not be assignable to Partial Records of incompatible types

Open pnappa opened this issue 10 months ago • 1 comments

🔎 Search Terms

keywords: required record, partial record, assignable, incompatible types

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about "Bugs" that have existed in TS for a long time.

⏯ Playground Link

https://www.typescriptlang.org/play/?target=6#code/N4AgsAUCIMYPYDsDOAXEAzOcBcJiWmgG0BrXVAJwEsEBzAXVwQFcBbAIwFMKCQBfEAF48vaKwCGtKjFwBGAAyKANLz4BuSL3jI07cRVwAFfSiriANgB5RIAEqd4FACaWA5BKkxXSkJRq0APl4AoQwsDQgtRCQ4c04AOnM4WgAKPQp4j2kAShAAejyQABUATwAHTiQYajK0GnRuJBAUAAsqJvEmvzofdmY0cRgUZgtzEpB2kBYObhBxNApmBFNWTkg+TUiIfChYaLRMOAAmXHtHF27aH2muChDhHcIQLJkQBWVVCKidEHSTkGMFFMFmsu2gZzgzjcL28vhQ1DoQV29zCxy+u20MTiiWSaX0R0ykhy+UKpQqVRqdQQDQoTVak06cIRV1+-TmQxG5jGEyaN1m8xAi2WVFW602QA

💻 Code

  const foo: {
    [k: string]: number
  } = {
    magic: 1000,
  };

  const bar: Partial<
    Record<'magic', string>
  > = foo;

  console.log(bar.magic) // Typescript infers this as string, but actually is number at runtime

The following also errors:

  const foo2: Record<string, number> = {
    magic: 1000,
  };

  const bar2: Partial<
    Record<'magic', string>
  > = foo2;

  console.log(bar2.magic) // Typescript infers this as string, but actually is number at runtime

🙁 Actual behavior

Typescript compiled, and it should not have. Assigning incompatible types that leads to runtime differences is unexpected.

🙂 Expected behavior

I was expecting it to fail compilation, with a mismatched type complaint.

Additional information about the issue

This led to an incomplete refactor not resulting in a compile error, which led to a crash in production.

pnappa avatar Mar 20 '25 04:03 pnappa

duplicate of #27144

jcalz avatar Mar 20 '25 15:03 jcalz

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

typescript-bot avatar Mar 23 '25 01:03 typescript-bot