Skip to content

Strings aren't supported in switch statements #2919

Closed
@mattjohnsonpint

Description

@mattjohnsonpint

Bug description

You should be able to use a switch statement for variables that are of type string, but it currently gives compiler errors:

This was mentioned lightly in #648 (comment) but I'll call it out as a bug.

Steps to reproduce

export function test(s: string): string {
  switch (s) {
    case 'foo':
      return 'abc';
    case 'bar':
      return 'def';
    default:
      return 'ghi';
  }
}
ERROR TS2322: Type '~lib/string/String' is not assignable to type 'u32'.
   :
 2 │ switch (s) {
   │         ~
   └─ in assembly/index.ts(2,11)

ERROR TS2322: Type '~lib/string/String' is not assignable to type 'u32'.
   :
 3 │ case 'foo':
   │      ~~~~~
   └─ in assembly/index.ts(3,10)

ERROR TS2322: Type '~lib/string/String' is not assignable to type 'u32'.
   :
 5 │ case 'bar':
   │      ~~~~~
   └─ in assembly/index.ts(5,10)

FAILURE 3 compile error(s)
Build failed.

A nullable string (ie. string | null) should also work, with null being a valid case, but fails in the same manner.

Workaround

Use consecutive if statements:

export function workaround(s: string): string {
  if (s === 'foo') {
    return 'abc';
  }
  if (s === 'bar') {
    return 'def';
  }
  return 'ghi';
}

... but this shouldn't be mandatory.

AssemblyScript version

v0.27.36

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions