Angular / 打字稿比较数字

Angular / typescript compare numbers

嗨,我在比较 2 个变量时遇到了问题:

console.log(simulation.population == 40000000); //true
console.log(simulation.initialInfectedNumber == 5); //true 
console.log(simulation.population < simulation.initialInfectedNumber); //true

都是数字:

export class Seirds {
  ...
  population: number;
  initialInfectedNumber: number;
  ...
  
}

有人可以解释一下它是如何工作的吗? (因为 4000 万不小于 5 :P),可能我在这个变量中有字符串但是当这个变量是数字时怎么可能。

编辑:

获取所有模拟对象

服务:

public getAllSimulations(): Observable<Seirds[]> {
    return this.httpClient.get<Seirds[]>(this.url + '/all');
  } 

组件方法:

this.service.getAllSimulations().subscribe(
      value => {
        this.simulations = value;
      }

API 回复:

[
    {
        "id": 1,
        "name": "example name",
        "population": 40000000,
        "initialInfectedNumber": 5,
        "daysOfSimulation": 2,
        "reproductionRate": 3.0,
        "immunityTime": 60.0,
        "incubationTime": 4.0,
        "naturalDeathRate": 0.0,
        "quarantineRate": 0.5,
        "birthRate": 0.0,
        "diseaseDuration": 15.0,
        "diseaseDeathRate": 0.1,
        "reductionByRestrictions": 0.2,
        "percentageOfPopulationWhenRestrictionsBegins": 1.0,
        "daysOfRestrictions": 30.0,
        "infectiousTime": 7.0,
        "timeOfOnsetOfSymptoms": 5.0,
        "timeOfDyingFromIncubation": 8.0,
        "records": [
            {
                "susceptible": 39999995,
                "exposed": 5,
                "infected": 0,
                "recovered": 0,
                "deaths": 0,
                "quarantined": 0
            },
            {
                "susceptible": 39999993,
                "exposed": 2,
                "infected": 5,
                "recovered": 0,
                "deaths": 0,
                "quarantined": 1
            }
        ]
    },
    {
        "id": 2,
        "name": "example name",
        "population": 40000000,
        "initialInfectedNumber": 5,
        "daysOfSimulation": 2,
        "reproductionRate": 3.0,
        "immunityTime": 60.0,
        "incubationTime": 4.0,
        "naturalDeathRate": 0.0,
        "quarantineRate": 0.5,
        "birthRate": 0.0,
        "diseaseDuration": 15.0,
        "diseaseDeathRate": 0.1,
        "reductionByRestrictions": 0.2,
        "percentageOfPopulationWhenRestrictionsBegins": 1.0,
        "daysOfRestrictions": 30.0,
        "infectiousTime": 7.0,
        "timeOfOnsetOfSymptoms": 5.0,
        "timeOfDyingFromIncubation": 8.0,
        "records": [
            {
                "susceptible": 39999995,
                "exposed": 5,
                "infected": 0,
                "recovered": 0,
                "deaths": 0,
                "quarantined": 0
            },
            {
                "susceptible": 39999993,
                "exposed": 2,
                "infected": 5,
                "recovered": 0,
                "deaths": 0,
                "quarantined": 1
            }
        ]
    }
]

服务组件:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SeirdsService {

  private url = 'http://localhost:8080/api/seirds';

  constructor(private httpClient: HttpClient) { }

  public getAllSimulations(): Observable<Seirds[]> {
    return this.httpClient.get<Seirds[]>(this.url + '/all');
  } 

  public addSimulation(simulation: Seirds): Observable<Seirds> {
    return this.httpClient.post<Seirds>(this.url, simulation);
  }

  public updateSimulation(simulation: Seirds): Observable<Seirds> {
    return this.httpClient.put<Seirds>(this.url, simulation);
  }

  public deleteSimulation(id: number): void {
    let endpoint = "/" + id;
    this.httpClient.delete(this.url + endpoint).subscribe();
  }
}

export class SeirdsRecord {
  susceptible: number;
  exposed: number;
  infected: number;
  recovered: number;
  deaths: number;
  quarantined: number;
}

export class Seirds {
  id: number;
  name: string;
  population: number;
  initialInfectedNumber: number;
  daysOfSimulation: number;
  reproductionRate: number;
  immunityTime: number;
  incubationTime: number;
  naturalDeathRate: number;
  quarantineRate: number;
  birthRate: number;
  diseaseDuration: number;
  diseaseDeathRate: number;
  reductionByRestrictions: number;
  percentageOfPopulationWhenRestrictionsBegins: number;
  daysOfRestrictions: number;
  infectiousTime: number;
  timeOfOnsetOfSymptoms: number;
  timeOfDyingFromIncubation: number;
  records: SeirdsRecord[];
}

您遇到了模拟对象的“问题”,首先,您需要使用 === 而不是 == 来比较值和类型。现在,您在模拟对象上拥有代表字符串的值,之后您将比较字符串和数字。

const simulation = { population: 40000000 , initialInfectedNumber: 5 };

console.log(simulation.population === 40000000); //true
console.log(simulation.initialInfectedNumber === 5); //true 
console.log(simulation.population < simulation.initialInfectedNumber); // false

编辑:

如果您没有正确使用类型,Typescript 将显示警告,并且不允许您比较字符串和数字。您需要“映射”从服务 HTTP 接收到的负载。

在您的代码中,您可以这样做:


this.service.getAllSimulations().subscribe(
      values => { // <- I suppose this is an array with your payload and make sure pouplation and initialInfectedNumber are numbers
        this.simulations = values.map((value) => new Seird(value.population, value. initialInfectedNumber));
  }
)

现在您将拥有 Seird[] 的模拟,但如果我的 Seird 构造函数接收到正确的类型:


class Seird {
  population: number; 
  initialInfectedNumber: number;

  constructor(population: number, initialInfectedNumber: number) {
    this.population = population;
    this.initialInfectedNumber = initialInfectedNumber;
  }
}

感谢@KennyXu 指出打字稿在运行时不检查的评论。请确保您的 API returns 个数字。