2

I've the following interface.

interface IDetails {
  name: string;
  age: number;
}

interface IConfig {
  appName: string;
  userDetails: IDetails;
  [key: string]: string | IDetails
}

const details: IConfig = {
  appName: 'test',
  userDetails: {
    name: 'xyz',
    age: 67,
  },
}

const t: string = 'userDetails'
const name: string = details[t].name
//                              ^^^^ 
// throws the following error
//
// Property 'name' does not exist on type 'string | IDetails'.
//  Property 'name' does not exist on type 'string'.

When I try to assign multiple types/interfaces to the key signature, I get this error. I know I can use [key: string]: any. But, I don't want to generalize it. Is there any possible way to make this work?

Link to TypeScript Playground

4
  • Can you cast to an IDetails: (<IDetails>details[t]).name Commented Dec 17, 2016 at 13:03
  • Thanks for the tip. Why string | IDetails is not working? Commented Dec 17, 2016 at 13:09
  • Why do you have [key: string]: string | IDetails? without it what you're trying would just work. Are you expecting more properties? Commented Dec 17, 2016 at 13:18
  • @NitzanTomer This is a simple use case. The t is the example will be dynamic. So, if I need to access the properties, I need to do this. Commented Dec 17, 2016 at 13:21

1 Answer 1

4

If you're going to dynamically access the properties of details, then you better use type guards:

function isDetails(obj: string | IDetails): obj is IDetails {
    return Object.keys(obj).length === 2 && typeof obj["name"] === "string" && typeof obj["age"] === "number";
}

Then you can do:

if (isDetails(details[t])) {
    // details[t].name should be fine with the compiler
}
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.