如果我有以下情況:
const c = class {
xyz = 123;
};
那么我可以這樣做:
new c().xyz // --> 123;
有沒有辦法提供一個物件來自動設定屬性?換句話說,我想做類似的事情:
const props = { foo: 'baz!', bar: 555 };
const c = class {
...props... // magically convert props to properties -- but how?
};
并且能夠做到:
new c().foo; // --> 'baz!'
new c().bar; // --> 555
這可能嗎?
uj5u.com熱心網友回復:
沒有一種完全型別安全的好方法。但是您可以Object.assign(this, props)在建構式中使用將所有這些屬性帶入實體,但 Typescript 并不真正知道該函式的作用或它如何影響型別。
是什么使它不那么好,以至于您還需要手動轉換結果。
您可以創建一個通用函式來為您執行此操作:
function makeClass<T>(props: T) {
return class {
constructor() {
Object.assign(this, props);
}
} as { new (): T }
}
const C = makeClass({ foo: 'baz!', bar: 555 });
const c = new C();
console.log(c.bar); // fine
console.log(c.foo); // fine
console.log(c.nope); // error
請注意,as { new (): T }這意味著這是一個值,您可以呼叫它new來回傳一個您是 props 的介面T。
如果您的類還具有其他屬性,則此解決方案可能會變得更加復雜,但這是一個開始。
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/449555.html
標籤:打字稿
下一篇:變數上getBoundingClientRect的Typescript型別,該變數可能是window或htmlElement
