0

Consider a type:

interface Base {
  a: number;
  b: number;
  c: number;
}

Now consider a type derived from it where c is not present: Omit<T, "c">:

type MyType<T> = Omit<T, "c">;

Now consider that I need to browse through the keys of A and do stuff:

const value: MyType<Base> = {
  a: 34,
  b: 67,
};

for (const k in value) {
  const el = value[k]; // Error
}

An error is raised:

const value: Pick<Base, "a" | "b">
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Pick<Base, "a" | "b">'.
  No index signature with a parameter of type 'string' was found on type 'Pick<Base, "a" | "b">'.ts(7053)

What is the best practice here?

Andry
  • 16,172
  • 27
  • 138
  • 246

1 Answers1

1

It is not related to Omit type. Try for ... in loop on any typed object, and you will have the same...

A kind of workaround is:

    for (const k in value) {
      const el = value[k as keyof typeof value]; 
    }

In this case you don't need to use any and you have your proper type in el - in this case number, but it will create a union type for all values in your interface.