0

Surely this is rudimentary TS, but I can't find the syntax.

I have a type:

type MyType = {
   prop1: string;
   prop2: string;
}

Now inside a function I have a variable of type MyType, but I need to dynamically get the value of a particular property on it, like:

const myMethod = (typeX: MyType, num: number) => {
    const property1 = typeX['prop${num}`]; // problem line!
}

The typescript error I'm seeing is:

TS7053 Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MyType'. No index signature with a parameter of type 'string' was found on type 'MyType'

Changing it to typeX['prop1'] works fine.

How do I cast that string as a property on MyType?

6
  • 1
    I think changing it to typeX['prop1'] makes it statically analyzable to the compiler, and it's recognizing the property as being valid. Commented Jan 27, 2020 at 20:29
  • 1
    What happens if you type typeX['invalid property']? Commented Jan 27, 2020 at 20:31
  • Interesting, you're correct - I get the same error with an invalid property. Seems like there should be a way to calm down the TS parser and just cast it somehow? Commented Jan 27, 2020 at 20:35
  • ((any)typeX)['prop${num}']? Commented Jan 27, 2020 at 20:36
  • I get a 'any' only refers to a type, but is being used as a value here with that. Commented Jan 27, 2020 at 20:41

1 Answer 1

1

You will need to use a type assertion here (similar to a cast in other languages but with no runtime semantics):


type MyType = {
   prop1: string;
   prop2: string;
}

const myMethod = (typeX: MyType, num: number) => {
    const property1 = typeX[`prop${num}` as keyof MyType]; 
}

Playground Link

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

Comments

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.