1

I am creating a model class in typescript:

class User {
  private 'google.com': string;
  private surname: string;
  private age: number;

  constructor(name: string, surname: string, age: number) {
    this['google.com'] = name;
    this.surname = surname;
    this.age = age;
  }
}

But instead of doing it that way, I am using shorthand (more info):

class User {
  constructor(
    private 'google.com': string, // Error: Identifier Expected. ts(1003) 
    private surname: string,
    private age: number
  ) {}
}

How do I escape the special character in 'google.com' in the shorthand method to eliminate the error?

ngaffer
  • 63
  • 10

1 Answers1

1

Short answer: You can't.


In this case:

class User {
  private 'google.com': string;
  constructor(name: string) {
    this['google.com'] = name
    console.log('got name', name);
  }
}

"google.com" is the name of a property on an object. Any string is valid as a property name, so this works just fine. And the name of the argument in the constructor function is name, which is a perfectly valid variable name.

However, in this case:

class User {
  constructor(private 'google.com': string) {
    console.log('got name', google.com); // this can't work
  }
}

"google.com" must also be the name of a variable, and variables have more strict rules on them. And in javascript a variable name must not have . character in it. Here there is not a way to tell a variable named google.com from accessing the com property of the google object.

Like all shorthand notation, it's short by making an assumption. The assumption in this case is that the name of the argument in your constructor is the same as the property name. So if you property name is not a valid variable name, you cannot use this shorthand syntax for that property.

So your use case breaks the assumption of this particular syntax. Which means you must use the more verbose syntax.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337