如何访问 TypeScript 中对象的数组字段?类型 'unknown' 必须有一个“[Symbol.iterator]()”方法,returns 一个迭代器

How can I access array field of an object in TypeScript? Type 'unknown' must have a '[Symbol.iterator]()' method that returns an iterator

我有一个辅助函数可以根据字段名更新表单,例如如果名称,则 form.name 将被更新。如果 user[0].name,则 form.users 的索引 0 的名称将被更新。但是我遇到了一个错误,下面的代码简化了它:

const example: Record<string, unknown> = {
    'a': 'haha',
    'b': [1,2,3],
};
const str = 'b.haha';
const tokens: string[] = str.split(".");
if (typeof example[tokens[0]][Symbol.iterator] === 'function') {
    const c = [...example[tokens[0]];
}

playground

我无法解决这个类型 'unknown' 必须有一个 'Symbol.iterator' 方法,returns 一个迭代器。 谢谢

您的问题是您将 Record 的第二个泛型参数设置为 unknown。在你的情况下,你可能希望它是 any 而不是:

const example: Record<string, any> = { // <- change is in this line
    'a': 'haha',
    'b': [1,2,3],
};
const str = 'b.haha';
const tokens: string[] = str.split(".");

if (typeof example[tokens[0]][Symbol.iterator] === 'function') {
    const c = [...example[tokens[0]];
    console.log(c);
}

Playground

unknownany IMO 之间的根本区别在于,您需要主动转换 unknown 类型的变量,而您可以对 [=14= 类型的变量执行任何操作].这使 unknown 更安全一些,因为如果您尝试使用 unknown 变量执行某些操作,尽管代码不知道该行是什么,但在编译时会出错。

就我个人而言,我会保留 unknown,实际上让 typescript 使用 type guards 发挥它的魔力,它会自动将 c 转换为 any[]:

const example: Record<string, unknown> = {
    'a': 'haha',
    'b': [1,2,3],
};
const str = 'b.haha';
const tokens: string[] = str.split(".");

const value = example[tokens[0]];

if (Array.isArray(value)) {
    const c = [...value];
    console.log(c);
}

Playground

您可能想阅读有关 unknown and how it compares to any 的文档。