我有這樣的課:(我正在使用 ts )
class FooClass
{
private _Id:number=0 ;
private _PrCode: number =0;
public get Id(): number {
return this._Id;
}
public set Id(id: number) {
this._Idproduit = id;
}
public get PrCode(): number {
return this._PrCode;
}
public set PrCode(prCode: number) {
this._PrCode = prCode;
}
}
如果創建這樣的反應變數,則在 i 組件內部:
const Model = ref<FooClass|null>(null);
當我想將它傳遞給一個函式時說:
let FooFunc = (FooClass|null) =>{//Do something}
像這樣:FooFunct(Model)
我得到這個錯誤
'{ Id: number; 型別的引數 PrCode:編號;} 不能分配給“FooClass”型別的引數。型別{ ID:號碼;PrCode:編號;} 缺少“FooClass”型別的以下屬性:{_Id,_PrCode}
就像 Ref 函式嘗試訪問“私有欄位”而不是 getter/setter 我該如何解決這個問題?
uj5u.com熱心網友回復:
這是在運行時不會發生的 TypeScript 錯誤,因此它與實際訪問的私有欄位無關。
私有欄位會影響 TypeScript 中的型別兼容性。這可用于強制不兼容并防止型別與相似型別意外匹配。這里需要做相反的事情,私有欄位需要從型別中排除。
它應該是:
type FooInterface = Pick<FooClass, keyof FooClass>
...
const Model = ref<FooInterface|null>(null);
let FooFunc = (FooInterface|null) =>{//Do something}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/473061.html
