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

4
  • @PatrickRoberts Did you read this question? It's completely different to what you marked as a duplicate... Commented Mar 4, 2019 at 2:24
  • I read the question. There is no property named x, just a property named propName. So either A.propName or const propName = "propName"; Commented Mar 4, 2019 at 2: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 Commented Mar 4, 2019 at 2: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. Commented Mar 4, 2019 at 2:31

1 Answer 1

2

This is possible, simply as:

const propName = "x";

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

A[propName]
Sign up to request clarification or add additional context in comments.

4 Comments

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.
This answer is correct; it is using 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).
And as for A[propName] compiling whether or not x exists on A: you would get a warning with --strict or --noImplicitAny modes.

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.