I'm attempting to utilize a variable from a destructuring expression as part of another object, but Typescript is not correctly recognizing its type.
Here is an example of what I am trying to achieve:
// defining a data structure
type Data = {
firstName: string;
lastName: string;
email: string;
tags: string[];
documents: [{ name: string; content: string }];
};
// generating dummy data
const getData = (): Data => ({
firstName: 'John',
lastName: 'Doe',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="573d383f397933383217322f363a273b327934383a">[email protected]</a>',
tags: ['javascript', 'typescript'],
documents: [{ name: 'cv.pdf', content: '...' }],
});
const processData = (data: {
// why is this type not capturing metadata from the rest operator?
[key: string]:
| string
| string[]
| { [key: string]: string }[]
| { [key: string]: string };
}): void => {
console.log(data);
};
// destructuring with rest
const { email, tags, documents, ...meta } = getData();
// why is Typescript not recognizing the type here?
processData({ email, tags, documents, meta });
and here is the error message that I am encountering
error TS2322: Type '{ firstName: string; lastName: string; }' is not assignable to type 'string | string[] | { [key: string]: string; } | { [key: string]: string; }[]'.
Type '{ firstName: string; lastName: string; }' is not assignable to type '{ [key: string]: string; }'.
Index signature is missing in type '{ firstName: string; lastName: string; }'.
50 processData({ email, tags, documents, meta });
~~~~
src/example.ts:37:3
37 [key: string]:
~~~~~~~~~~~~~~
38 | string
~~~~~~~~~~~~
...
40 | { [key: string]: string }[]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
41 | { [key: string]: string };
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The expected type comes from this index signature.
Can anyone point out what I might be doing incorrectly?