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

我正在尝试将解构表达式中的变量用作另一个对象的一部分,但 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}[];
}; 

https://stackoverflow.com/questions/60318710/

相关文章:

c# - 使用 csc.exe 构建时访问内部异常

google-cloud-storage - gcsfuse 不会写入文件夹

python-3.x - 从目录流式传输图像并将预测与 tensorflow 中的文件名相关联

python - BIGQUERY - 整数范围分区表中的未分区分区

django - 使用 xlswriter || 自动调整列宽 Django

flutter - 有没有办法在 Flutter 中控制系统音乐?

reactjs - 'react-hot-loader/babel' 是做什么用的?

javascript - Jest/ react - TypeError : Cannot read

python - Kivy Filechooser 在屏幕上滚动重叠文本

angular - 使用 GitHub Actions 运行 Angular e2e 测试会抛出 "