大致过程就是检查 b 上有没有和 a 相同的属性,如果有就赋值给 a.
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,
};
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'.
}
}
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'.
}
}
除了像下面这样给 A 加上 [propName: string] 之外还有别的解决办法吗?
interface A {
[propName: string]: string|number;
foo: string,
bar: number,
};