typescriptassemblyscript

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). And all this function wants to do is push the ID of the position parameter onto the array.

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". Which makes...no sense to me.


Solution

  • AssemblyScript has stricter null safety during deducing non-nullability than TS for now.

    So in AS you can fix by using exclamation !:

    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

    Due to this, in complex cases may be unsound. TypeScript ok with this because TS has already unsoundness in many cases.