gpt4 book ai didi

typescript - 当我尝试使用对象解构结果的变量时,TS 无法识别其类型

转载 作者:行者123 更新时间:2023-12-05 07:12:51 24 4
gpt4 key购买 nike

我正在尝试将解构表达式中的变量用作另一个对象的一部分,但 Typescript 无法正确识别其类型。

这是我正在做的一个例子:

// some data structure
type Data = {
firstName: string;
lastName: string;
email: string;
tags: string[];
documents: [{ name: string; content: string }];
};

// just generate dummy data
const getData = (): Data => ({
firstName: 'John',
lastName: 'Doe',
email: 'john.doe@example.com',
tags: ['javascript', 'typescript'],
documents: [{ name: 'cv.pdf', content: '...' }],
});

const processData = (data: {
// why this type does not cover meta from rest operator?
[key: string]:
| string
| string[]
| { [key: string]: string }[]
| { [key: string]: string };
}): void => {
console.log(data);
};

// destructure with rest
const { email, tags, documents, ...meta } = getData();

// why TS does not recognize type here?
processData({ email, tags, documents, meta });

这是我得到的错误

 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.

我做错了什么?

最佳答案

原因是因为在 TS 中类型不是密封的,这意味着它们表示必需的字段但不允许多余的属性。因此,可以向 meta 添加不符合您在 processData 中期望的索引签名的属性(即通过 Object.assign (元,{ id: 4234 }))。

一个可能的修复方法是将 meta 解构为一个新对象。

processData({ email, tags, documents, {...meta} });

或为数据中的附加属性定义约束:

type Data = {
firstName: string;
lastName: string;
email: string;
tags: string[];
documents: [{ name: string; content: string }];
[key: string]: string | string[] | {name: string, content: string}[];
};

关于typescript - 当我尝试使用对象解构结果的变量时,TS 无法识别其类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60318710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com