Skip to content

Array spread to object and interate over array type. #39726

Closed
@fayzzzm

Description

@fayzzzm

TypeScript Version: 3.9.2

Description
Hey, there. Here is the thing.

  1. This is very strange when I want to spread array in an object, all prototype methods go to object too.
  2. When you want to iterate over type any[] you will get [k: number]: a union of all types of your array

Code

  1. Issue:
const arr = [1, 2, 3, 4];

const obj = { ...arr };
// it's fine, just do it :)
obj.pop();

But when ts compiles to js, we know that object doesn't have pop(if there is no property pop set by a developer), but the spread of array causes this thing to happen in typescript.

  1. Issue:
const arr = [1, 2, "ts", true];
const obj = {
  a: 1,
  b: 1,
  c: 'ts',
  d: true
}

type type<T> = T extends any[]
  ? { [K in keyof T]: T[K] }
  : T extends object
  ? { [K in keyof T]: T[K] }
  : never;

// (string|number|boolean)[]
// no keys :(
type test = type<typeof arr>;
// brings types with keys
type test1 = type<typeof obj>

Why I've mentioned this because some want to iterate array { [K in keyof T]: T[K] extends number ? 'hey' : 'no' }, he/she will always get 'no'[] if the array has various types.

Expected behavior:
1 Issue: Should give an error, that pop() is not a function of an object.
2. Issue: There should be keys that show, that arr[idx] has this kind of type not a union of all types of an array.
Something like this: {0: number, 1: number, 2: string, 3:boolean}

Actual behavior:

  1. Issue: obj.pop(); works fine when we spread array into an object.
  2. Issue: array will show (number | string | etc. ...)[]

Playground Link:

  1. https://www.typescriptlang.org/play/index.html?ssl=4&ssc=11&pln=1&pc=1#code/MYewdgzgLgBAhgJwTAvDA2gRgDQwEy4DMuALALoDcAsAFC2iSwgBGAVqjAN4wB0fiyAL7UaLVjwAOICQAoAlBSA
  2. https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=20&pc=30#code/MYewdgzgLgBAhgJwTAvDA2gRgDQwEy4BEUEhuUCArgKYC6A3ALABQoksIARgFaowDeLGPABcMHEJicxE5sOBiA5CUXZJAEzEUaLAL4sWUAJ4AHajGNmAPABUAfHxsxqADyjUw6iPDBH0tSQB+AQwAaRgASzAYAGtqIxAAMxgbWjEbdFDaGH05GHTnNw8vGC5uamAoIJDMyOi4hOTU9Mzs3OExMGoAN2oEJmYWAHohmAAKaAQogHMAHzBKAFtOPtnOEBAAG2o4MABKf2HRsBBY+O8RMclhEZCABk6llYRcTEflvtw8MUmZ3ABmMTrLY7MC6GAQAAWIEom3UUnM0w28MMpnM7mgfEs1Cs2KS8CQdgGt04UzA0282O8AHcIlBIWcjBBUWYLNRoJgsWjcWj8WU7EA

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions