microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.1k stars 12.37k forks source link

No error with Partial<Record<number, {}>> in object spreading #37337

Open Rendalf opened 4 years ago

Rendalf commented 4 years ago

TypeScript Version: 3.8.3

Search Terms: [type inference], [partial], [record], [object spreading]

Code

type Point = {
  x: number
  y: number
}

type Space = Partial<Record<number, Point>>

function addPointReducer(point: Point, pointId: number, prevSpace: Space): Space {
  const prevPoint = prevSpace[pointId]

  return {
    ...prevPoint,
    [pointId]: point,
  }
}

Expected behavior: Should throw an error on ...prevPoint because Point doesn't equal to Space.

Actual behavior: No error.

Playground Link: https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=17&pc=1#code/C4TwDgpgBACg9gSwHbCgXigbwFBSgDwC4okBXAWwCMIAnXKEYsq27AX221EigGUwAhgGNoGGAJrAEAgDYAeAEoQhcGgBM5zajQA0sRCgB8hztgBmpJEKlwkUAWrXxkwJWtIiaACjAHgxZxQ9XxcASTUmCm1gmggAN35hCGJEkQBKFMERLHoVJABnVDBYuMDUDGL41IgAbRCUcIBdTjxY4FIaOxw8PAA6fsrSvx16PDq-JuJ64BG8Dg4gA

Related Issues:

RyanCavanaugh commented 4 years ago

@ahejlsberg I've been looking at a few of these and don't feel like I have a good handle on our policy on computed property keys in these positions. Are they ever excess? How are they checked?

wclr commented 4 years ago

Too explained this issue on SO with spreading with number keys. https://stackoverflow.com/questions/63037175/typescript-some-strange-spread-allowed-that-breaks-typings

Why this works without error:

interface S {
  chats: {
    [ChatId: number]: {
      name: string
      messages: []
    }
  }
}

const s1: S = {
  chats: {
    [1123]: {
      name: 'some',
      messages: [],
    },
  },
}

const s2: S = {
  chats: {
    ...s1,
  },
}

console.log('s2', s2)

Ts playground

This definilty gives illegal result: s2 { chats: { chats: { '1123': [Object] } } }

Andarist commented 1 year ago

This is likely highly related to https://github.com/microsoft/TypeScript/issues/27273