3

I have an object, which is of type defined there:

interface IObject extends IIndexable {
  foo?: string;
  foo2?: string;
  foo3?: string;
}

My IIndexable looks like this:

interface IIndexable {
  [key: string]: string;
}

I want to access its properties using brackets notation like this:

let object: IObject = {};
object["foo"] = "bar"; 

The problem is that key defined in IIndexable can only be of type of string or number and because my objects' keys are all optional, they are of type string | undefined. Error message I get is:

Property 'fullName' of type 'string | undefined' is not assignable to string index type 'string'.

I cannot make my objects' keys not optional, because my object sometimes can be empty. I also tried to make objects' type IObject | {}, but that way I still cannot access its properties.

Is there any way to solve this?

5
  • Why do you need extends IIndexable part? Commented Jul 4, 2020 at 13:24
  • @Aleksey L. I use IIndexable in other places where I need to access objects using brackets notation. It's the same as putting [key: string]: string; line at the end of interface where I need this access. Commented Jul 4, 2020 at 13:34
  • You can access props with brackets notation without defining index signature Commented Jul 4, 2020 at 13:37
  • Without it I get this error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IObject'. No index signature with a parameter of type 'string' was found on type 'IObject'. Commented Jul 4, 2020 at 13:39
  • 1
    Yes, that's because you're trying to access it with random string instead of known property Commented Jul 4, 2020 at 13:45

1 Answer 1

3

You can define type alias (instead of interface) and use intersection with the IIndexable:

type IObject = IIndexable & {
  foo?: string;
  foo2?: string;
  foo3?: string;
}

Playground

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.