1

Is something like this possible?

const propName = "x";

class A {
    static propName = 1
    // equivalent to static x = 1
}

A[propName] // evaluates to 1

or would it be (typeof A)[propName]?


For obvious reasons, this is not a duplicate of this question

Tobiq
  • 2,489
  • 19
  • 38
  • @PatrickRoberts Did you read this question? It's completely different to what you marked as a duplicate... – Tobiq Mar 04 '19 at 02:24
  • I read the question. There is no property named `x`, just a property named `propName`. So either `A.propName` or `const propName = "propName";` – Patrick Roberts Mar 04 '19 at 02:25
  • @PatrickRoberts You should re-open this question. I have no idea why you think that other question is even related - it's not even TypeScript – Tobiq Mar 04 '19 at 02:27
  • That is not equivalent to `static x = 1`, FYI. The meaning of `static propName = 1` does not change just because a string variable `propName` exists. – Patrick Roberts Mar 04 '19 at 02:31

1 Answers1

2

This is possible, simply as:

const propName = "x";

class A {
    static [propName] = 1
    // equivalent to static x = 1
}

A[propName]
Tobiq
  • 2,489
  • 19
  • 38
  • 1) Don't assume it's me downvoting. 2) `A[propName]` will compile regardless of whether `x` exists on `A` or not. Try it yourself. This is not type-safe, see [this](https://stackoverflow.com/q/43740513/1541563). – Patrick Roberts Mar 04 '19 at 02:34
  • [Yes](https://stackoverflow.com/search?q=user%3A1541563+%5Btypescript%5D) – Patrick Roberts Mar 04 '19 at 02:36
  • This answer is correct; it is using [computed properties](https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#computed-properties), which TypeScript understands as long as the value of the property is statically known as a literal type (so `let propName = "x";` would fail because `propName` would be `string`). – jcalz Mar 04 '19 at 13:42
  • And as for `A[propName]` compiling whether or not `x` exists on `A`: you would get a warning with `--strict` or `--noImplicitAny` modes. – jcalz Mar 04 '19 at 13:45