简体   繁体   English

错误 TS2322:类型 '~lib/array/Array<~lib/string/String> | null' 不可分配给类型 '~lib/array/Array<~lib/string/String>'

[英]ERROR TS2322: Type '~lib/array/Array<~lib/string/String> | null' is not assignable to type '~lib/array/Array<~lib/string/String>'

Holder has an array of strings (holder.positions). Holder 有一个字符串数组(holder.positions)。 And all this function wants to do is push the ID of the position parameter onto the array.而这个函数想要做的就是将位置参数的 ID 推送到数组中。

Here is my function这是我的功能

function updateHolder(holder: Holder, position: Position): void {
    if(holder.positions == null){
        const positions: string[] = [];
        holder.positions = positions;
    }
    holder.positions.push(position.id);
}

The error that I get is我得到的错误是

ERROR TS2322: Type '~lib/array/Array<~lib/string/String> | null' is not assignable to type '~lib/array/Array<~lib/string/String>'.


holder.positions.push(position.id);
   ~~~~~~~~~~~~~~~~

Which seems to be saying "the thing you're trying to push onto the array is either a string array or null, but it has to be a string array".这似乎是在说“您要推送到数组上的东西是字符串数组或 null,但它必须是字符串数组”。 Which makes...no sense to me.这对我来说……毫无意义。

AssemblyScript has stricter null safety during deducing non-nullability than TS for now.与 TS 相比,AssemblyScript 在推断不可为空性期间具有更严格的空安全性。

So in AS you can fix by using exclamation !因此,在 AS 中,您可以使用感叹号来修复! :

export function updateHolder(holder: Holder, position: Position): void {
    if (holder.positions == null) {
        holder.positions = [];
    }
    holder.positions!.push(position.id); // add "!"
}

Btw Dart also can't prove such cases: https://dartpad.dev/df0be72a941f4d515a5ecfec6a8ee7d9顺便说一句,Dart 也无法证明这种情况: https ://dartpad.dev/df0be72a941f4d515a5ecfec6a8ee7d9

Due to this, in complex cases may be unsound.因此,在复杂的情况下可能不健全。 TypeScript ok with this because TS has already unsoundness in many cases. TypeScript 可以这样,因为 TS 在很多情况下已经不健全了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM