【发布时间】:2019-06-15 08:12:47
【问题描述】:
我有一个接口 (A),里面有一个接口 (B)。接口 A 用作接口 A 的数组。
当我更新特定接口 A 中的接口 B 时,任何接口 A 中的所有相同接口 B 也会更新。
如果我使用相同的方法但设置了一个接口A属性,是正确的。
例如,我制作了一个智能代码。
我们让客户分分钟吃掉一些 x 产品。我需要知道我需要多少个农场才能配得上所有的客户。
Client 作为产品,eatByMinute 和 howMany(howMany Client)。 作为产品的农场,makeByMinute(按分钟制造多少产品)。
我在“客户端界面”中注入“农场界面”以获取大数据对象。我要计算“我需要多少个农场”。
如果我在“农场接口”中设置 HowManyNeed,则所有“客户端接口”中的所有相同“农场接口”都采用相同的值。
如果我在“客户端界面”中设置了 HowManyFarmNeed,则每个值都是正确的
逻辑是:
初始化->开始->CountFarmNeed->结束
const farms: IFarm[] =
[{
"name": "AppleFarm",
"product": "Apple",
"makeByMinute": 2
}, {
"name": "PerryFarm",
"product": "Perry",
"makeByMinute": 1
}
];
interface IFarm {
name: string,
product: string,
makeByMinute: number,
howManyNeed?: number
}
interface IClient {
name: string,
eatByMinute: number,
whatDoesEat: string,
howMany: number,
farm?: IFarm,
howManyFarmNeed?: number
}
export class Client {
static get(name: string, eatByMinute: number, whatDoesEat: string, howMany: number): IClient {
return {name: name, 'eatByMinute': eatByMinute, 'whatDoesEat': whatDoesEat, 'howMany': howMany}
}
}
export class Farm {
static getByProduct(product: string): IFarm {
//@ts-ignore: array.Find can return "Undefined" BUT function return IFarm. In this exemple is ok
return farms.find((item: IFarm) => item.product == product);
}
}
export default class Problem {
static init() {
let clients: IClient[] = [
Client.get('men', 0.25, 'Apple', 2000),
Client.get('women', 0.30, 'Perry', 1500),
Client.get('dog', 0.25, 'Apple', 3000),
];
clients = this.start(clients);
clients = this.countFarmNeed(clients);
this.end(clients)
}
static start(clients: IClient[]):IClient[] {
for (let c in clients) {
clients[c] = this.loadFarm(clients[c]);
}
return clients
}
static loadFarm(client: IClient): IClient {
client.farm = Farm.getByProduct(client.whatDoesEat);
return client;
}
static countFarmNeed(clients: IClient[]):IClient[] {
for (let c in clients) {
//@ts-ignore: clients[].farm possibly undifined. In this exemple is ok
clients[c].farm.howManyNeed = (clients[c].howMany * clients[c].eatByMinute) / clients[c].farm.makeByMinute;
//@ts-ignore: clients[].farm possibly undifined. In this exemple is ok
clients[c].howManyFarmNeed = (clients[c].howMany * clients[c].eatByMinute) / clients[c].farm.makeByMinute;
}
return clients
}
static end(clients:IClient[]){
console.log(clients)
}
}
我期待
[0].farm.howManyNeed:250;
[1].farm.howManyNeed:450;
[2].farm.howManyNeed:375;
但实际有:
[0].farm.howManyNeed:375;
[1].farm.howManyNeed:450;
[2].farm.howManyNeed:375;
【问题讨论】:
标签: typescript pointers interface