代码是:

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

我得到以下TS错误:

string类型的实参不能赋值给never类型的形参。

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


当前回答

这个错误还有一个原因。 如果你在使用connect()()包装组件后导出,那么props可能会给出typescript errorSolution:我没有探索太多,因为我可以选择用useSelector钩子替换连接函数 例如

/* Comp.tsx */
interface IComp {
 a: number
}

const Comp = ({a}:IComp) => <div>{a}</div>

/* ** 

below line is culprit, you are exporting default the return 
value of Connect and there is no types added to that return
value of that connect()(Comp) 

** */

export default connect()(Comp)


--
/* App.tsx */
const App = () => {
/**  below line gives same error 
[ts] Argument of type 'number' is not assignable to 
parameter of type 'never' */
 return <Comp a={3} />
}

其他回答

另一种方法是:

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

您需要指定数组是什么,因为result =[]的返回类型为任意[]。通常情况下,你想要避免任何类型,因为根据微软的说法,它们意味着被用作“逃生舱口”。

结果是一个字符串数组的对象。

在最新版本的angular中,你必须定义变量的类型:

如果它是一个字符串,你必须这样做: 公开信息:string =""; 如果是数字: 公共n: number=0; 如果一个string的表: 公共标签:字符串[]= []; 如果用数字表表示: 公共标签:number[]=[]; 如果是混合表: 公共标签:any[] = []; ……Etc(用于其他类型的变量) 如果你没有定义变量的类型:默认情况下,类型为never

注意:在你的情况下,你必须知道你的表必须包含的变量类型,并选择正确的选项(如选项3,4,5)。

从"compilerOptions"中删除"strictNullChecks": true或在tsconfig中将其设置为false。这些错误会像任何东西一样消失,你的应用程序将成功编译。

免责声明:这只是一个变通方案。此错误仅在null检查未正确处理时出现,这在任何情况下都不是完成工作的好方法。

你需要输入result到字符串const result的数组:string[] =[];。