【问题标题】:Typescript refactoring打字稿重构
【发布时间】:2022-01-04 01:29:11
【问题描述】:

此代码工作正常。但这对我来说看起来很奇怪。尤其是这部分``` const city = [].concat(...locationCities).includes('London'); 如果(城市 === 真)

api客户端:

export interface apiRequest {
  locations: LocationOptions[];

}
interface FOLocations {
  locationId: number;
}

interface LocationResult {
  location: FOLocations[];
  address: Address;
}
interface LocationResult {
country:string;
city:string;
}
export const locationCheck = async (
  apiKey: string,
  payload: apiRequest
): Promise<LocationResult[]> => {
  let response = await axios.post<LocationResult[]>(
    `api...`,
    payload
  );
  return response.data;

运行代码:

  const locationPayload : apiRequest = {
      locations:[{ cityName: "London"},{cityName: "New York"},{cityName: "Paris"}],
    };
    const locationResponse = await locationCheck(apiKey,locationPayload);
    const locationCities = locationResponse.map((location) => location.address.map(options => {return options.country}));
    console.log(locationCities);
    const city = [].concat(...locationCities).includes('London');
    console.log(city);
  if(city === true){
      console.log(`London location exist`);
    }else {
      throw new Error(
            "error"
      );
    }

输出:

true
London location exist

【问题讨论】:

    标签: arrays reactjs typescript refactoring


    【解决方案1】:

    我认为你可以删除这一行:

    const city = [].concat(...locationCities).includes('London');
    

    然后替换这个:

    if(city === true){
      // ...
    

    有了这个:

    if(locationCities.includes('London')){
      // ...
    

    【讨论】:

      猜你喜欢
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多