0

I can't seem to access attributes, see below:

type ValidAttributes = "FOO" | "BAR" | "BAZ";

interface MyInterface {
  attributes: {
    [s in keyof ValidAttributes]: string;
  };
}

const doSomething = (data: MyInterface): void => {
  const foo = data.attributes.FOO;
  //Error:(10, 31) TS2339: Property 'FOO' does not exist on type '{ toString: string; charAt: string; charCodeAt: string; concat: string; indexOf: string; lastInde...'.

  const bar = data.attributes["BAR"];
  //Error:(13, 15) TS7017: Element implicitly has an 'any' type because type '{ toString: string; charAt: string; charCodeAt: string; concat: string; indexOf: string; lastInde...' has no index signature.
}

I also have a linter which autocorrects the last code into the other format. This could be disabled if it is the only way.

1 Answer 1

1

Change your interface definition:

type ValidAttributes = "FOO" | "BAR" | "BAZ";

interface MyInterface {
  attributes: {
    [s in ValidAttributes]: string;
  };
}

When you use keyof in ValidAttributes, you're getting the properties of type String, because ValidAttributes is a union of strings. You don't want that, you want the properties to be one of the strings, not the properties of the union of strings, so you just need s in ValidAttributes, not s in keyof ValidAttributes.

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

1 Comment

Thanks. The use of "keyof" was a bummer. ;-)

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.