3

There are two objects like this:

interface A {
  foo: string;
  bar: number;
};
const a: A = {
  foo: 'a',
  bar: 1,
};

interface B extends Partial<A> {
  [propName: string]: any;
}
const b: B = {
  foo: 'b',
  bar: 2,
  c: 3,
};

I want to assign the property of b to a.
I tried some methods but all got errors.
1

for (const key of Object.keys(a)) {
  if (b[key]) {
    a[key] = b[key]; //Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'A'.
  }
}

2

for (const key of Object.keys(a)) {
  const k = key as keyof typeof a;
  if (b[k]) {
    a[k] = b[k]; // Type 'string | number' is not assignable to type 'never'.
  }
}

I don't want to use "[propName: string]" like this.
Is there any other solution?

interface A {
  [propName: string]: string|number;
  foo: string,
  bar: number,
};
Bob
  • 369
  • 3
  • 10

0 Answers0