我有一B堂課extends A。我正在嘗試復制A到B(因為B具有與 相同的所有屬性(以及更多屬性)A)。
例子:
class TypeA {
propX: number = 0;
propY: number = 0;
}
class TypeB extends TypeA {
propZ: number = 0;
}
let A: TypeA = {propX: 1, propY: 2};
let B: TypeB = new TypeB();
//Here I want to copy A's properties onto B
Object.keys(A).forEach(prop => B[prop] = A[prop]); //this how we did it on older version of typescript, still works in this example but won't compile in my new project
//now set B's non-shared property
B.propZ = 3;
//desired output {propX: 1, propY: 2, propZ: 3}
console.log(B);
那一Ojbect.keys(A) ...行是我們在一個具有早期 TS 版本的專案上所做的,但現在它不會編譯。事實上,在這個 TS fiddle中,它將成功運行并獲得預期的結果。但是,該行有錯誤。在我的 Angular 專案中,它根本無法編譯。
我現在可以/應該怎么做?
另外,是的,我確實看過這個類似的問題,但沒有找到可行的解決方案。那里接受的“解決方案”對我來說似乎不正確,盡管我不理解它,但我嘗試將它實施到我的示例中:
let key: keyof TypeA;
for (key in A) {
A = {
...A,
[key]: B[key]
}
}
這對我來說真的沒有多大意義,但我還是在發帖前試過了???♂?
謝謝你的時間。
uj5u.com熱心網友回復:
舊的“嘿編譯器閉嘴我知道我在做什么”。
Object.keys(A).forEach((prop) => { (B as any)[prop] = (A as any)[prop]; });
或者
Object.keys(A).forEach((prop) => { (<any>B)[prop] = (<any>A)[prop]; });
有人可能會說這是不好的做法,但我認為在這種情況下沒問題。
uj5u.com熱心網友回復:
您可以將鍵存盤在只讀陣列中,并在復制值時迭代鍵。在定義基類時,您還可以使用此陣列來約束基類的形狀:
TS游樂場
// Define the common keys in a readonly array:
const keysA = ['propX', 'propY'] as const;
type KeyA = typeof keysA[number];
// Define the base class using an "implements" clause to ensure that
// its shape includes the keys above:
class TypeA implements Record<KeyA, number> {
propX: number = 0;
propY: number = 0;
}
class TypeB extends TypeA {
propZ: number = 0;
}
let A: TypeA = {propX: 1, propY: 2};
// Just a note: A is not an instance of TypeA since you did not construct it:
console.log({'A instanceof TypeA': A instanceof TypeA}); // false
let B: TypeB = new TypeB();
// This is ok because the keys are string literals in the readonly array:
for (const key of keysA) B[key] = A[key];
B.propZ = 3;
console.log({B}); // { propX: 1, propY: 2, propZ: 3 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495087.html
