You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is very strange when I want to spread array in an object, all prototype methods go to object too.
When you want to iterate over type any[] you will get [k: number]: a union of all types of your array
Code
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.
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:
Issue: obj.pop(); works fine when we spread array into an object.
Issue: array will show (number | string | etc. ...)[]
Second is usual behavior types for array items - union of all types, but if you need to see exact types for fixed length array you need to use tuple types. Example
TypeScript Version: 3.9.2
Description
Hey, there. Here is the thing.
type any[]
you will get[k: number]: a union of all types of your array
Code
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.
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:
obj.pop();
works fine when we spread array into an object.Playground Link:
The text was updated successfully, but these errors were encountered: