SQL 查詢 -
const currency = req.query.currency; - the query options: "BTCUSD" | "ETHUSD" | "LTCUSD"
const allPrices = await Crypto.findAll({ attributes: [currency, 'createdAt'], order: [['createdAt', 'ASC']], raw: true });
在Crypto-
class Crypto extends Sequelize.Model<IDBCryptoAttributes> implements IDBCryptoAttributes {
public id!: number;
public BTCUSD!: number;
public ETHUSD!: number;
public LTCUSD!: number;
public readonly createdAt!: Date;
}
allPrices 物件例如 -
{
BTCUSD: '4526.341078145248',
createdAt: 2021-10-22T20:51:23.000Z,
},
{
BTCUSD: '4600.428393851253',
createdAt: 2021-10-22T20:52:24.000Z,
},
在將第一個變數值allPrices發送到客戶端之前,將其添加到陣列中 -
const toClient = allPrices.map((item, index) => {
if (index === 0) {
return item;
}
return {
...item,
price: item[currency] allPrices[0][currency],
}
});
toClient 物件例如 -
{
BTCUSD: '4526.341078145248',
createdAt: 2021-10-22T20:51:23.000Z,
price: 69989.82615963052
},
{
BTCUSD: '4600.428393851253',
createdAt: 2021-10-22T20:52:24.000Z,
price: 70063.91347533654
},
所以我想像這樣發送給客戶 -
res.status(200).send({
success: true,
message: "Successfully retrieved Historic prices",
data: toClient.map((price) => ({
price: price.price,
createdAt: price.createdAt,
})),
});
問題是 -
Property 'price' does not exist on type 'Crypto | { price: number; id: number; BTCUSD: number; ETHUSD: number; LTCUSD: number; createdAt: Date; _attributes: IDBCryptoAttributes; _creationAttributes: IDBCryptoAttributes; isNewRecord: boolean; sequelize: Sequelize; _model: Model<...>; }'.
Property 'price' does not exist on type 'Crypto'.ts(2339)
uj5u.com熱心網友回復:
正如錯誤所述,該型別Crypto不包含屬性價格,因此型別Crypto | AnyOtherType并不總是包含此屬性。
換句話說,為了從聯合型別參考屬性,它需要在該型別的所有組件之間通用。
具體來說,問題出在以下代碼段中,您將更改應用于除第一個元素之外的所有元素,這會導致聯合型別。也許你可以解釋為什么對第一個元素進行特殊處理。
const toClient = allPrices.map((item, index) => {
if (index === 0) {
return item;
}
return {
...item,
price: item[currency] allPrices[0][currency],
}
});
但是,如果您接受undefined或null代替第一個元素的價格,那么您可以執行以下操作,以檢查物件是否包含該price屬性。
const data = toClient.map((price) => ({
price: "price" in price ? price.price : undefined,
createdAt: price.createdAt,
}))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/332669.html
標籤:打字稿
上一篇:在nodejs中讀取屬性檔案
下一篇:拖動檔案并選擇要反應的檔案
