'TypeScript difference between original object and spreaded object
there is a riddle about Typescript I cannot understand:
const randomFn = (arg: Record<string, unknown>): string => 'kappa'
export type Values = {
key: string;
};
const values: Values = {
key: 'kappa'
}
const { ...spread } = values;
randomFn(values)
randomFn(spread) // produce Index signature for type 'string' is missing in type '{ transaction: string; }'.(2345)
Why is Typescript producing errors for spread object when in my understanding it typing should be the same. If we inspect the object in playgroud it is exactly the same for TS compiler. Both original and spreaded.
TS version 4.5.4. Reproduction in Type Script Playground
EDIT: also doing double spread to make it work again .
randomFn({...spread}) // NO error
Solution 1:[1]
Spreading loses the type because it has no guarantee that the type of the spread object is the same. Consider this:
const { excluded, ...rest } = object;
Clearly rest can't be the same type as object; there is a key missing!
You can also think of it like this:
const [excluded, ...rest] = array;
That's why spread is not type Values.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hittingonme |
