0

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.

Steve
  • 4,457
  • 12
  • 48
  • 89
  • 1
    It really makes all sense. Imagine an array of string `const arr: string[] = []`, and after fetching an api, you either get a user object with a property .username that is either a string or null. if you want to add that username to the array you have to make sure it's a string first, for example using using `if(typeof(obj.username) === "string") arr.push(obj.username)`, this way it will add to the array only if it's a string. – Staxlinou Jul 22 '22 at 00:51
  • @MalikLahlou I had a similar thought. But when I add if(position.id==null){return;} before my push, I still get the same error – Steve Jul 22 '22 at 01:47
  • Same with that more explicit type check that you suggested – Steve Jul 22 '22 at 01:48
  • Hmmm, try adding an excalamation point after `position.id`, it's to tell typescript that this is absolutely not null in no case `.push(position.id!)`` – Staxlinou Jul 22 '22 at 01:55
  • That still gets me the same error, plus a "INFO AS210: Expression is never 'null'.", which feels like typescript is mocking me – Steve Jul 22 '22 at 02:00
  • 1
    bruh at first it tells you that it can null and not that it will never be null im out – Staxlinou Jul 22 '22 at 02:04

1 Answers1

1

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.

MaxGraey
  • 351
  • 2
  • 6