什么是“不可分配给类型 never 的参数"?打字稿错误? [英] What is "not assignable to parameter of type never" error in typescript?

查看:37
本文介绍了什么是“不可分配给类型 never 的参数"?打字稿错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码是:

const foo = (foo: string) => {
  const result = []
  result.push(foo)
}

我收到以下 TS 错误:

I get the following TS error:

[ts] 'string' 类型的参数不能分配给 'never' 类型的参数.

[ts] Argument of type 'string' is not assignable to parameter of type 'never'.

我做错了什么?这是一个错误吗?

What am I doing wrong? Is this a bug?

推荐答案

你所要做的就是将你的 result 定义为一个字符串数组,如下所示:

All you have to do is define your result as a string array, like the following:

const result : string[] = [];

不定义数组类型,默认为never.所以当你试图向它添加一个字符串时,它是一个类型不匹配,所以它抛出了你看到的错误.

Without defining the array type, it by default will be never. So when you tried to add a string to it, it was a type mismatch, and so it threw the error you saw.

这篇关于什么是“不可分配给类型 never 的参数"?打字稿错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆