TypeScript 中 Property ‘push’ does not exist on type 错误
当我们对不是数组的值调用 push()
方法时,会出现错误“Property ‘push’ does not exist on type”。 要解决此错误,请确保仅对数组调用 push()
方法或更正调用该方法的变量类型。
以下是发生上述错误的 2 个示例。
const obj = {};
// ⛔️ Error: Property 'push' does not exist on type '{}'.ts(2339)
obj.push('hello');
// ---------------------------------------------------------------
// 👇️ it's an array, but has incorrect type
const arr = ['one', 'two', 'three'] as unknown as { name: string };
// ⛔️ Property 'push' does not exist on type '{ name: string; }'.ts(2339)
arr.push('four');
在第一个示例中,我们调用了一个对象的 Array.push
方法,这导致了错误。
如果要向对象添加属性,请确保对象的类型允许这样做并使用点或括号表示法。
const obj: { name: string } = { name: '' };
// ⛔️ Error: Property 'push' does not exist on type '{}'.ts(2339)
// obj.push('hello');
obj.name = 'Alice';
console.log(obj); // 👉️ {name: 'Alice'}
否则,要开始调试,console.log
将打印 push
方法的值并确保它是一个数组。
const obj: { name: string } = { name: '' };
console.log(Array.isArray(obj)); // 👉️ false
console.log(Array.isArray([1, 2, 3])); // 👉️ true
如果我们确定调用
push
方法的值是一个数组,请尝试重新启动 IDE 和开发服务器。 VSCode 经常出现故障并需要重启。
如果值有时可以是一个对象而有时是一个数组,则在调用 push
方法时必须使用类型保护。
const maybeArray = Math.random() > 0.5 ? [1, 2, 3] : { name: 'Tom' };
if (Array.isArray(maybeArray)) {
maybeArray.push(4);
console.log(maybeArray); // 👉️ [1, 2, 3, 4]
}
Array.isArray
方法用作类型保护。
如果满足条件,TypeScript 知道
maybeArray
变量存储一个数组并允许我们调用push()
方法。
如果我们尝试直接在变量上调用该方法,我们会得到“属性‘push’在类型上不存在”错误,因为变量可能不是数组。
如果我们断定调用 push
方法的变量是数组,则需要更正其类型。
// 👇️ it's an array, but has incorrect type
const arr = ['one', 'two', 'three'] as unknown as { name: string };
// ⛔️ Property 'push' does not exist on type '{ name: string; }'.ts(2339)
arr.push('four');
arr
变量存储一个数组,但是,它具有不同的类型,因此 TypeScript 不允许我们调用 push()
方法。
如果我们无法控制变量的类型并且知道它是一个数组,则可以使用类型断言。
const arr = ['one', 'two', 'three'] as unknown as { name: string };
(arr as unknown as any[]).push('four');
console.log(arr); // 👉️ ['one', 'two', 'three', 'four']
当我们有关于 TypeScript 不知道的值类型的信息时,使用类型断言。
我们有效地告诉 TypeScript arr 变量将是
any[]
类型并且不用担心它。
如果这是导致我们的情况出现错误的原因,最好找出错误类型的来源。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。