AssemblyScript / assemblyscript

A TypeScript-like language for WebAssembly.
https://www.assemblyscript.org
Apache License 2.0
16.86k stars 657 forks source link

Any name for index type signatures like TS (not just "key"). #1972

Open trusktr opened 3 years ago

trusktr commented 3 years ago

Input:

class MyClass {
    [coolKeys: number]: boolean
}

const o = new MyClass 

o[1] = true

TypeScript playground (works)

AssemblyScript playground (error)

The error had me thinking that it was an unsupported feature:

;; ERROR TS1005: 'key' expected.
;; 
;;      [coolKeys: number]: boolean

I thought "a key is required here? I put a key there, but it must not support it".

I didn't realize that it is saying I need to actually name my key "key". Changing it to "key" gets past that error, although in the following example it has some other error I don't understand:

AssemblyScript playground (no more "'key' expected" error)

In asdom I did not have the new error that the previous example has, and it all is working well (NodeList bindings with [] indexed access).

willemneal commented 3 years ago

As far as I'm aware, the error is because the parser expects key, but the compiler ignores it since it will use the operator overload method to check the type of the key.

trusktr commented 3 years ago

@willemneal In asdom I am not having that error, and I am using both, which is working well. Without the index signature, TypeScript will complain and VS Code will show red squigglies.

Here is the implementation (see that it has both):

https://github.com/lume/asdom/blob/01a9dc3c6259a9418a50f53766b68c54bb47f5c1/assembly/NodeList.ts

And here is the usage (no errors in VSCode or AS):

https://github.com/lume/asdom/blob/01a9dc3c6259a9418a50f53766b68c54bb47f5c1/example/assembly/index.ts#L89-L91

trusktr commented 3 years ago

Oooh, the second error is ERROR TS2542: Index signature in type 'module/MyClass' only permits reading.. In the asdom example I'm only reading (and it is meant to be read-only in that case too), so no wonder I didn't see that error there.

Here is the corrected example with no errors: playground.

willemneal commented 3 years ago

Looking at your code, just wanted to mention that currently ! results in a runtime check. So another good feature request is to add a compile flag to just treat it like TS does.

trusktr commented 3 years ago

Plus in TypeScript this is how one actually makes the index type read-only: readonly [key: number]: Node | null. It needs some alignment TLC.