一种类型的对象指向另一种打字稿mysql

时间:2020-06-08 18:52:20

标签: typescript node-mysql

我将mysql lib与typescript一起使用,但是我认为,这个问题不仅与mysql有关。我需要从数据库中获取所有表和特定行的ID。为了使用Promise,我为此编写了一个简单的包装程序,因此它看起来像这样:

export interface IAroma {
  title: string,
  title_description: string,
  brand: string,
  since: number,
  sex: string,
  country: string,
  collection: string,
  composition: {
    top: string[],
    middle: string[],
    bottom: string[],
  },
  description: string,
  similar: string[],
  slug: string,
  images: string[],
}

export interface IDbValue {
  id: number
}

interface IAromaFromDb extends IAroma, IDbValue{}

const p_query = (sql:string, obj?:any) : Promise<mysql.OkPacket> => {
  return new Promise((resolve, reject) => {
    pool.query(sql, obj, (err, data) => {
      if(err) reject(data)
      resolve(data)
    })
  })
}

export const getAromas = async () : Promise<IAromaFromDb[]> => {
  return p_query("SELECT * FROM `aroma_aromas` WHERE 1");
}


export const getAromaById = async (id:number) : Promise<IAromaFromDb> => {
  return (await p_query("SELECT * FROM `aroma_aromas` WHERE `id` = ?", [id]))[0];
}

p_query("SELECT * FROM aroma_aromas WHERE 1")将返回如下数组:

  RowDataPacket {
  id: ...,
  title: '...',
  title_description: '',
  brand: '...',
  since: '...',
  sex: '...',
  country: '...',
  collection: '...',
  description: '...',
  similar: '...',
  slug: '...',
  composition: '...'
}

但是在功能getAromas中,我遇到了打字错误:Type 'OkPacket' is missing the following properties from type 'IAromaFromDb[]': length, pop, push, concat, and 26 more.

p_query("SELECT * FROM aroma_aromas WHERE id = 123")将返回如下数组:

  RowDataPacket {
  id: ...,
  title: '...',
  title_description: '',
  brand: '...',
  since: '...',
  sex: '...',
  country: '...',
  collection: '...',
  description: '...',
  similar: '...',
  slug: '...',
  composition: '...'
}

但是在功能getAromaById中,我遇到了打字错误:Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'OkPacket'.   Property '0' does not exist on type 'OkPacket'.

那么,如何告诉打字稿在我的sql请求中我得到了接口IAromaFromDb的对象或数组?

0 个答案:

没有答案