ウェブサイト検索

TypeScript - 「[]」演算子でプロパティの型をどのように定義しますか?


このようなものが二つあります。

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,
};

私はbのプロパティをaに割り当てたいです。
いくつかの方法を試しましたが、すべてエラーになりました。
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'.
  }
}

このように「[propName: string]」を使いたくありません。
他に方法はありますか?

interface A {
  [propName: string]: string|number;
  foo: string,
  bar: number,
};