![](/img/trans.png)
[英]Solid JS with Typescript - "as" prop \ "component" prop
[英]TypeScript + Solid JS Abstract Class
给定一个抽象 Class 用作 createStore 的类型,为什么我的方法 calcUtilisation 未定义? 如何使用 createStore 的同一 class 中的方法使用数据类型?
abstract class Account {
abstract name: String;
abstract creditUsed: number;
abstract creditLimit: number;
public calcUtilisation() {
return (this.creditUsed / this.creditLimit) * 100;
}
}
interface State {
accounts: [Account] | []
}
const [store, setStore] = createStore<State>({
accounts: []
});
const addAccount: Store<State> = (account: Account) => {
setStore({...store, accounts: [
...store.accounts,
account
]});
return store;
}
addAccount({ name:"Barclays", creditUsed: 11600, creditLimit: 13600 });
console.log(store.accounts.calcUtilisation)
因为store.accounts
是一个数组,所以它没有calcUtilisation
方法。 您应该访问此数组的某些元素,例如:
console.log(store.accounts[0].calcUtilisation)
但是之后的事件将是未定义的,因为这里没有定义此方法:
addAccount({ name:"Barclays", creditUsed: 11600, creditLimit: 13600 });
您传递给addAccount
的 Object 没有calcUtilisation
方法。 您应该在此 object 中手动指定它,或者创建一个具体的 class 构造函数来扩展您的抽象 class 并在此处创建一个实例,例如:
class ConcreteAccount extends Account {
constructor(accountObject) {
this.name = accountObject.name;
this.creditUsed = accountObject.creditUsed;
this.creditLimit = accountObject.creditLimit;
}
}
addAccount(new ConcreteAccount({ name:"Barclays", creditUsed: 11600, creditLimit: 13600 }));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.