0

From typescriptlang.org:

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

This is false.

Here, I have the error:

An index expression argument must be of type 'string', 'number', 'symbol', or 'any'

This is caused by the [ inline-map ] expression:

test = { true: 'Y', false: 'N', undefined: 'IDK', null: 'Nah', 0: 'none' }[ true ];

Isn't a Boolean a type "<any>"??? Pretty infuriating, since I use this syntax left right & center.

Moreover, the following works just fine:

{ true: 'Y', false: 'N', undefined: 'IDK', null: 'Nah', 0: 'none' }[ undefined ];
{ true: 'Y', false: 'N', undefined: 'IDK', null: 'Nah', 0: 'none' }[ null ];

The colloquial, "Anything that's legal JavaScript is perfectly legal TypeScript" is outright a false statement.

Obviously, I can write it as:

{ true: 'Y', false: 'N', undefined: 'IDK', null: 'Nah', 0: 'none' }[ ''+true ];

But why is Boolean not of type any???

Is this a bug of TypeScript?

Has this been reconciled in TS 2.1?

Can I correct this issue in tsconfig.json or another way?

10
  • 2
    Boolean and any are different types. Boolean is compatible with any, but it does not say compatible with type string, ... or any, it says must be of type .... Also, errors reported by typescript do not prevent it from compiling your source code to javascript (unless you set --noEmitOnError compiler option explicitly), so yes, it is a superset of JavaScript. Commented Jan 19, 2017 at 19:20
  • 1
    does obj[<any>bool] work? in general, claims made by frameworks are often exaggerated... Commented Jan 19, 2017 at 19:23
  • 1
    @dandavis It does appear to work. Commented Jan 19, 2017 at 19:35
  • 1
    This may help you: stackoverflow.com/questions/41750390/… Commented Jan 19, 2017 at 19:47
  • 1
    From my experience, is a relationship is not very meaningful for structural types (all types in typescript except enums are structural). is a is one-way only and transitive (A is a B and B is a C means A is a C). Structural typing is completely different beast, it's modeled with A is assignable to B relation, and any was deliberately made 2-way compatible with any type, so you have weird thing where int is assignable to any and any is assignable to string but not int assignable to string Commented Jan 19, 2017 at 21:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.