0

When I try to run the following code that uses a private field, I get an "Invalid character" error at the position of #.

class MyClass {
    #x =  10;
}

This is my tsconfig.json:

{
    "compilerOptions": {
        "target": "esnext",
    …
}

I get this error:

2:5 - error TS1127: Invalid character.

Why is that, and how can I fix it?

7
  • There aren't that many characters in the code you posted. Which one looks the most invalid to you? Which one haven't you ever seen in any TypeScript example? Hint: the error message gives you the line and column of the invalid character. Commented Aug 24, 2019 at 21:54
  • @JBNizet Why it is impossible to use the symbol # if it is in javascript? Commented Aug 24, 2019 at 22:00
  • Because the JavaScript language designers decided so. Commented Aug 24, 2019 at 22:03
  • @JBNizet Any javascript code will always work in typescript.so say the developers of typescript. Commented Aug 24, 2019 at 22:10
  • But that's not valid JavaScript. Maybe it will be, at some time. Commented Aug 24, 2019 at 22:16

1 Answer 1

3

You still have to use private keyword:

class MyClass {
    private x =  10;
}

Implement ES Private Fields is on the TypeScript roadmap in the Future section (so, I guess, earliest in version 3.7).

Sign up to request clarification or add additional context in comments.

4 Comments

the future, what is better to use in typescript # or private ?
@SilicumSilium this is speculation, but I think # will take off, considering that's what un-typed JavaScript will most likely use.
@grooveplex I think so too.Thank you.
I think private will continue being predominantly used. It more readable and better fit other keywords public and protected. But it's good there will be a choice. Let's see what happens.

Your Answer

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