类型“未知[]”缺少类型“ [字符串,未知]”的以下属性:0,1ts(2739)

时间:2019-11-14 00:46:43

标签: node.js typescript

我遇到错误类型'unknown []',缺少类型'[string,unknown]'的以下属性:acc.concat([k,... v]第15行的0,1ts(2739) .map((s)=> ${s} ${k})])));

我是打字稿新手,这让我陷入了一段时间。

我正在尝试从

形式的对象转换json对象
 "message": {
      "arctic":[],
      "atlantic":[
             "north",
             "south",
      ],
      "indian":[],
      "pacific":[
             "north",
             "south",
      ],
      "southern":[],
}  

到形式为

的对象
"message": [
 "artic",
 "atlantic",
 "north atlantic",
 "south atlantic",
 "indian",
 "pacific",
 "north pacific",
 "south pacific",
 "southern"
]
import fetch from 'node-fetch'
interface Response {
  statusCode: number
}
interface ListResponse extends Response {
  body: DogList
}
interface DogList {
  message: Array<string> 
  status: string
}
function flat(object:any) {
  return Object
      .entries(object)
      .reduce((acc,[k, v]) => acc.concat([k, ...v.map((s) => `${s} ${k}`)])); //problem here
}

export async function handler(): Promise<ListResponse> {
  try {
    const res = await fetch('https://dog.ceo/api/breeds/list/all')

    const payload: DogList = await res.json()
    if (res.ok) {
      const ret:string[]=flat(payload.message)
      return {
        statusCode: res.status,
        body: {
            message: ret,
            status: payload.status
        }
      }
    }
    return {
      statusCode: res.status,
      body: payload,
    }
  } catch (err) {
    return {
      statusCode: err.code,
      body: {
        message: err.message,
        status: err.status,
      },
    }
  }
}

0 个答案:

没有答案